

/*============================================*/
//                    myLongLastingOperation = function(time) {
//                     var  myDeferred = $.Deferred();
//                     setTimeout(function(){myDeferred.resolve();}, time);
//                     return myDeferred.promise();
//                    }
//                    myPromise = $.when( 
//                        myLongLastingOperation(500),
//                        myLongLastingOperation(1700));
//
//                    myPromise.done(function(){document.write('done')});
                    /*============================================*/
//                    function setMyVar(){
//                          var dfd = $.Deferred();
//                          setTimeout(function(){ myVar = 10; dfd.resolve(); }, 1000)
//                         return dfd.promise();
//                    }
//                    setMyVar().done(function(){  console.log('The value of myVar is:  ' + myVar )  })
                    /*============================================*/




var eventManager = function(config){
    var config=(config && 
                 config.namespace && 
                 config.namespace.separator && 
                 tools.isString(config.namespace.separator) && 
                 !tools.isEmptyString(config.namespace.separator) &&
                 config.namespace.separator.length ===1) ? config : {
        namespace:{separator:'.'}};
    
    var __vars={};
    var __registered_events={};
    var __registered_actions={};
    
    var __eventObject={id:'',name:'',owner:'',data:{}};
    
    /**
     * 
     */
    var __registerEvents=function(/*array*/events){
        // return the events array (arg1) with IDs for each event
    };
    
    /**
     * 
     */
    var __unregisterEvents=function(/*array*/events){
        //return true on success
    };
    
    /**
     * riseEvent or TriggerEvent
     */
    var __riseEvent=function(/*eventObect*/event){};
    
    /**
     * 
     */
    var __registerEventActions=function(eventObject, action, actionOwner){};
    
    /**
     * 
     */
    var __removeEventActions=function(/*eventObect*/eventObject, actions){};
    
    
    
    return {
        
    };
    
    
};







/*
CryptoJS v3.0.2
code.google.com/p/crypto-js
(c) 2009-2012 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/

var MD5_LOADED=1;

var CryptoJS=CryptoJS||function(o,q){var l={},m=l.lib={},n=m.Base=function(){function a(){}return{extend:function(e){a.prototype=this;var c=new a;e&&c.mixIn(e);c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),j=m.WordArray=n.extend({init:function(a,e){a=
this.words=a||[];this.sigBytes=e!=q?e:4*a.length},toString:function(a){return(a||r).stringify(this)},concat:function(a){var e=this.words,c=a.words,d=this.sigBytes,a=a.sigBytes;this.clamp();if(d%4)for(var b=0;b<a;b++)e[d+b>>>2]|=(c[b>>>2]>>>24-8*(b%4)&255)<<24-8*((d+b)%4);else if(65535<c.length)for(b=0;b<a;b+=4)e[d+b>>>2]=c[b>>>2];else e.push.apply(e,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,e=this.sigBytes;a[e>>>2]&=4294967295<<32-8*(e%4);a.length=o.ceil(e/4)},clone:function(){var a=
n.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var e=[],c=0;c<a;c+=4)e.push(4294967296*o.random()|0);return j.create(e,a)}}),k=l.enc={},r=k.Hex={stringify:function(a){for(var e=a.words,a=a.sigBytes,c=[],d=0;d<a;d++){var b=e[d>>>2]>>>24-8*(d%4)&255;c.push((b>>>4).toString(16));c.push((b&15).toString(16))}return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-4*(d%8);return j.create(c,b/2)}},p=k.Latin1={stringify:function(a){for(var b=
a.words,a=a.sigBytes,c=[],d=0;d<a;d++)c.push(String.fromCharCode(b[d>>>2]>>>24-8*(d%4)&255));return c.join("")},parse:function(a){for(var b=a.length,c=[],d=0;d<b;d++)c[d>>>2]|=(a.charCodeAt(d)&255)<<24-8*(d%4);return j.create(c,b)}},h=k.Utf8={stringify:function(a){try{return decodeURIComponent(escape(p.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return p.parse(unescape(encodeURIComponent(a)))}},b=m.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=j.create();
this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=h.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,c=b.words,d=b.sigBytes,f=this.blockSize,i=d/(4*f),i=a?o.ceil(i):o.max((i|0)-this._minBufferSize,0),a=i*f,d=o.min(4*a,d);if(a){for(var h=0;h<a;h+=f)this._doProcessBlock(c,h);h=c.splice(0,a);b.sigBytes-=d}return j.create(h,d)},clone:function(){var a=n.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});m.Hasher=b.extend({init:function(){this.reset()},
reset:function(){b.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);this._doFinalize();return this._hash},clone:function(){var a=b.clone.call(this);a._hash=this._hash.clone();return a},blockSize:16,_createHelper:function(a){return function(b,c){return a.create(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return f.HMAC.create(a,c).finalize(b)}}});var f=l.algo={};return l}(Math);
(function(o){function q(b,f,a,e,c,d,g){b=b+(f&a|~f&e)+c+g;return(b<<d|b>>>32-d)+f}function l(b,f,a,e,c,d,g){b=b+(f&e|a&~e)+c+g;return(b<<d|b>>>32-d)+f}function m(b,f,a,e,c,d,g){b=b+(f^a^e)+c+g;return(b<<d|b>>>32-d)+f}function n(b,f,a,e,c,d,g){b=b+(a^(f|~e))+c+g;return(b<<d|b>>>32-d)+f}var j=CryptoJS,k=j.lib,r=k.WordArray,k=k.Hasher,p=j.algo,h=[];(function(){for(var b=0;64>b;b++)h[b]=4294967296*o.abs(o.sin(b+1))|0})();p=p.MD5=k.extend({_doReset:function(){this._hash=r.create([1732584193,4023233417,
2562383102,271733878])},_doProcessBlock:function(b,f){for(var a=0;16>a;a++){var e=f+a,c=b[e];b[e]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360}for(var e=this._hash.words,c=e[0],d=e[1],g=e[2],i=e[3],a=0;64>a;a+=4)16>a?(c=q(c,d,g,i,b[f+a],7,h[a]),i=q(i,c,d,g,b[f+a+1],12,h[a+1]),g=q(g,i,c,d,b[f+a+2],17,h[a+2]),d=q(d,g,i,c,b[f+a+3],22,h[a+3])):32>a?(c=l(c,d,g,i,b[f+(a+1)%16],5,h[a]),i=l(i,c,d,g,b[f+(a+6)%16],9,h[a+1]),g=l(g,i,c,d,b[f+(a+11)%16],14,h[a+2]),d=l(d,g,i,c,b[f+a%16],20,h[a+3])):48>a?(c=
m(c,d,g,i,b[f+(3*a+5)%16],4,h[a]),i=m(i,c,d,g,b[f+(3*a+8)%16],11,h[a+1]),g=m(g,i,c,d,b[f+(3*a+11)%16],16,h[a+2]),d=m(d,g,i,c,b[f+(3*a+14)%16],23,h[a+3])):(c=n(c,d,g,i,b[f+3*a%16],6,h[a]),i=n(i,c,d,g,b[f+(3*a+7)%16],10,h[a+1]),g=n(g,i,c,d,b[f+(3*a+14)%16],15,h[a+2]),d=n(d,g,i,c,b[f+(3*a+5)%16],21,h[a+3]));e[0]=e[0]+c|0;e[1]=e[1]+d|0;e[2]=e[2]+g|0;e[3]=e[3]+i|0},_doFinalize:function(){var b=this._data,f=b.words,a=8*this._nDataBytes,e=8*b.sigBytes;f[e>>>5]|=128<<24-e%32;f[(e+64>>>9<<4)+14]=(a<<8|a>>>
24)&16711935|(a<<24|a>>>8)&4278255360;b.sigBytes=4*(f.length+1);this._process();b=this._hash.words;for(f=0;4>f;f++)a=b[f],b[f]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360}});j.MD5=k._createHelper(p);j.HmacMD5=k._createHmacHelper(p)})(Math);
//==============================================

var application = {
   enableEncryption:false
};

application.server = {
    main:{
        startingProtocol:'http://', /* This MUST be https::// on production site */
        protocol:'http://',
        URL:'localhost/pfp/pfp/',
        IpAddress:'127.0.0.1',
        entryPoint:'index.php',
        controller:'index.php',
        requestType:'POST',
        encryption:{
            key:'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef01234567890abcdef0123456789',
            type:'rabbit',
            method:'rabbit'
        }
        
    }
};

application.client = {
    user:{
        username:'',
        password:''
    },
    
    encryption:{
            status:function(){
                if (application.client.tools.isNullOrUndef(application.client.user.password) || 
                    application.client.user.password==''){
                    return false;
                }
                
                if (application.enableEncryption){ return true; }
                
                return false;
            },
            
            key:function(){
                var key='';
                if (application.client.encryption.status()){
                    var password_sha512 = application.client.tools.crypto.sha512(application.client.user.password);
                    var l = password_sha512.length;
                    for (var i=1; i<=l; i++){
                        if (i%2!=0){
                            key += password_sha512.substr(i-1, 1);
                        }
                    }
                }
                //alert(key);
                return key;
            },
            
            type:'rabbit',
            method:'rabbit'
    },
    
    
};

application.server.request2server = function(){
    return {
        entryPoint:{
            name:'',
            controller:{
                name:'',
                action:{
                    name:'',
                    param:''
                }
            }
        },    
        data:''
    };
};
application.server.request = function(request_object){
    var data_to_send = JSON.stringify(request_object);
    
    if (application.client.encryption.status()){
        data_to_send = application.client.tools.crypto.rabbit().encrypt(data_to_send, application.client.encryption.key());
    };
    
    return $.ajax({
        url : application.server.main.protocol+application.server.main.URL+'/',
        type: application.server.main.requestType,
        data: {req: data_to_send.toString() },
        dataType: "json"
/*        beforeSend: function(x) { if (x && x.overrideMimeType){ x.overrideMimeType("application/j-son;charset=UTF-8"); }},
        success: function(data, textStatus, jqXHR){},
        complete: function(jqXHR, textStatus){},
        error:  function(jqXHR, textStatus, errorThrown){ alert('Error: '+JSON.stringify(jqXHR, null, 4)); } */
    });
};

application.client.tools.crypto = {}

application.client.tools.crypto.sha512 = function(data){
    /*
    CryptoJS v3.0.2
    code.google.com/p/crypto-js
    (c) 2009-2012 by Jeff Mott. All rights reserved.
    code.google.com/p/crypto-js/wiki/License
    */
    var CryptoJS=CryptoJS||function(a,g){var m={},e=m.lib={},q=e.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var d=new a;b&&d.mixIn(b);d.$super=this;return d},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var k in a)a.hasOwnProperty(k)&&(this[k]=a[k]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),r=e.WordArray=q.extend({init:function(a,b){a=
    this.words=a||[];this.sigBytes=b!=g?b:4*a.length},toString:function(a){return(a||n).stringify(this)},concat:function(a){var b=this.words,d=a.words,c=this.sigBytes,a=a.sigBytes;this.clamp();if(c%4)for(var i=0;i<a;i++)b[c+i>>>2]|=(d[i>>>2]>>>24-8*(i%4)&255)<<24-8*((c+i)%4);else if(65535<d.length)for(i=0;i<a;i+=4)b[c+i>>>2]=d[i>>>2];else b.push.apply(b,d);this.sigBytes+=a;return this},clamp:function(){var k=this.words,b=this.sigBytes;k[b>>>2]&=4294967295<<32-8*(b%4);k.length=a.ceil(b/4)},clone:function(){var a=
    q.clone.call(this);a.words=this.words.slice(0);return a},random:function(k){for(var b=[],d=0;d<k;d+=4)b.push(4294967296*a.random()|0);return r.create(b,k)}}),y=m.enc={},n=y.Hex={stringify:function(a){for(var b=a.words,a=a.sigBytes,d=[],c=0;c<a;c++){var i=b[c>>>2]>>>24-8*(c%4)&255;d.push((i>>>4).toString(16));d.push((i&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c+=2)d[c>>>3]|=parseInt(a.substr(c,2),16)<<24-4*(c%8);return r.create(d,b/2)}},l=y.Latin1={stringify:function(a){for(var b=
    a.words,a=a.sigBytes,d=[],c=0;c<a;c++)d.push(String.fromCharCode(b[c>>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c++)d[c>>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return r.create(d,b)}},da=y.Utf8={stringify:function(a){try{return decodeURIComponent(escape(l.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return l.parse(unescape(encodeURIComponent(a)))}},h=e.BufferedBlockAlgorithm=q.extend({reset:function(){this._data=
    r.create();this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=da.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(k){var b=this._data,d=b.words,c=b.sigBytes,i=this.blockSize,l=c/(4*i),l=k?a.ceil(l):a.max((l|0)-this._minBufferSize,0),k=l*i,c=a.min(4*k,c);if(k){for(var h=0;h<k;h+=i)this._doProcessBlock(d,h);h=d.splice(0,k);b.sigBytes-=c}return r.create(h,c)},clone:function(){var a=q.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});e.Hasher=
    h.extend({init:function(){this.reset()},reset:function(){h.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);this._doFinalize();return this._hash},clone:function(){var a=h.clone.call(this);a._hash=this._hash.clone();return a},blockSize:16,_createHelper:function(a){return function(b,d){return a.create(d).finalize(b)}},_createHmacHelper:function(a){return function(b,d){return ea.HMAC.create(a,d).finalize(b)}}});
    var ea=m.algo={};return m}(Math);
    (function(a){var g=CryptoJS,m=g.lib,e=m.Base,q=m.WordArray,g=g.x64={};g.Word=e.extend({init:function(a,e){this.high=a;this.low=e}});g.WordArray=e.extend({init:function(e,y){e=this.words=e||[];this.sigBytes=y!=a?y:8*e.length},toX32:function(){for(var a=this.words,e=a.length,n=[],l=0;l<e;l++){var g=a[l];n.push(g.high);n.push(g.low)}return q.create(n,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),g=a.words=this.words.slice(0),n=g.length,l=0;l<n;l++)g[l]=g[l].clone();return a}})})();
    (function(){function a(){return q.create.apply(q,arguments)}var g=CryptoJS,m=g.lib.Hasher,e=g.x64,q=e.Word,r=e.WordArray,e=g.algo,y=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317),
    a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291,
    2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899),
    a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470,
    3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],n=[];(function(){for(var l=0;80>l;l++)n[l]=a()})();e=e.SHA512=m.extend({_doReset:function(){this._hash=r.create([a(1779033703,4089235720),a(3144134277,2227873595),a(1013904242,4271175723),a(2773480762,1595750129),a(1359893119,2917565137),a(2600822924,725511199),a(528734635,4215389547),a(1541459225,327033209)])},_doProcessBlock:function(a,e){for(var h=this._hash.words,g=h[0],k=h[1],b=h[2],d=h[3],c=h[4],i=h[5],m=
    h[6],h=h[7],q=g.high,r=g.low,W=k.high,K=k.low,X=b.high,L=b.low,Y=d.high,M=d.low,Z=c.high,N=c.low,$=i.high,O=i.low,aa=m.high,P=m.low,ba=h.high,Q=h.low,t=q,o=r,E=W,C=K,F=X,D=L,T=Y,G=M,u=Z,p=N,R=$,H=O,S=aa,I=P,U=ba,J=Q,v=0;80>v;v++){var z=n[v];if(16>v)var s=z.high=a[e+2*v]|0,f=z.low=a[e+2*v+1]|0;else{var s=n[v-15],f=s.high,w=s.low,s=(w<<31|f>>>1)^(w<<24|f>>>8)^f>>>7,w=(f<<31|w>>>1)^(f<<24|w>>>8)^(f<<25|w>>>7),B=n[v-2],f=B.high,j=B.low,B=(j<<13|f>>>19)^(f<<3|j>>>29)^f>>>6,j=(f<<13|j>>>19)^(j<<3|f>>>29)^
    (f<<26|j>>>6),f=n[v-7],V=f.high,A=n[v-16],x=A.high,A=A.low,f=w+f.low,s=s+V+(f>>>0<w>>>0?1:0),f=f+j,s=s+B+(f>>>0<j>>>0?1:0),f=f+A,s=s+x+(f>>>0<A>>>0?1:0);z.high=s;z.low=f}var V=u&R^~u&S,A=p&H^~p&I,z=t&E^t&F^E&F,fa=o&C^o&D^C&D,w=(o<<4|t>>>28)^(t<<30|o>>>2)^(t<<25|o>>>7),B=(t<<4|o>>>28)^(o<<30|t>>>2)^(o<<25|t>>>7),j=y[v],ga=j.high,ca=j.low,j=J+((u<<18|p>>>14)^(u<<14|p>>>18)^(p<<23|u>>>9)),x=U+((p<<18|u>>>14)^(p<<14|u>>>18)^(u<<23|p>>>9))+(j>>>0<J>>>0?1:0),j=j+A,x=x+V+(j>>>0<A>>>0?1:0),j=j+ca,x=x+ga+
    (j>>>0<ca>>>0?1:0),j=j+f,x=x+s+(j>>>0<f>>>0?1:0),f=B+fa,z=w+z+(f>>>0<B>>>0?1:0),U=S,J=I,S=R,I=H,R=u,H=p,p=G+j|0,u=T+x+(p>>>0<G>>>0?1:0)|0,T=F,G=D,F=E,D=C,E=t,C=o,o=j+f|0,t=x+z+(o>>>0<j>>>0?1:0)|0}r=g.low=r+o|0;g.high=q+t+(r>>>0<o>>>0?1:0)|0;K=k.low=K+C|0;k.high=W+E+(K>>>0<C>>>0?1:0)|0;L=b.low=L+D|0;b.high=X+F+(L>>>0<D>>>0?1:0)|0;M=d.low=M+G|0;d.high=Y+T+(M>>>0<G>>>0?1:0)|0;N=c.low=N+p|0;c.high=Z+u+(N>>>0<p>>>0?1:0)|0;O=i.low=O+H|0;i.high=$+R+(O>>>0<H>>>0?1:0)|0;P=m.low=P+I|0;m.high=aa+S+(P>>>0<I>>>
    0?1:0)|0;Q=h.low=Q+J|0;h.high=ba+U+(Q>>>0<J>>>0?1:0)|0},_doFinalize:function(){var a=this._data,e=a.words,h=8*this._nDataBytes,g=8*a.sigBytes;e[g>>>5]|=128<<24-g%32;e[(g+128>>>10<<5)+31]=h;a.sigBytes=4*e.length;this._process();this._hash=this._hash.toX32()},blockSize:32});g.SHA512=m._createHelper(e);g.HmacSHA512=m._createHmacHelper(e)})();     

    var hash = CryptoJS.SHA512(data);
    return hash.toString(CryptoJS.enc.Hex);
//    return hash.toString(CryptoJS.enc.Base64); 

}

application.client.tools.crypto.aes = function(){

    /*
    CryptoJS v3.0.2
    code.google.com/p/crypto-js
    (c) 2009-2012 by Jeff Mott. All rights reserved.
    code.google.com/p/crypto-js/wiki/License
    */
    var CryptoJS=CryptoJS||function(p,h){var i={},l=i.lib={},r=l.Base=function(){function a(){}return{extend:function(e){a.prototype=this;var c=new a;e&&c.mixIn(e);c.$super=this;return c},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var c in a)a.hasOwnProperty(c)&&(this[c]=a[c]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.$super.extend(this)}}}(),o=l.WordArray=r.extend({init:function(a,e){a=
    this.words=a||[];this.sigBytes=e!=h?e:4*a.length},toString:function(a){return(a||s).stringify(this)},concat:function(a){var e=this.words,c=a.words,b=this.sigBytes,a=a.sigBytes;this.clamp();if(b%4)for(var d=0;d<a;d++)e[b+d>>>2]|=(c[d>>>2]>>>24-8*(d%4)&255)<<24-8*((b+d)%4);else if(65535<c.length)for(d=0;d<a;d+=4)e[b+d>>>2]=c[d>>>2];else e.push.apply(e,c);this.sigBytes+=a;return this},clamp:function(){var a=this.words,e=this.sigBytes;a[e>>>2]&=4294967295<<32-8*(e%4);a.length=p.ceil(e/4)},clone:function(){var a=
    r.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var e=[],c=0;c<a;c+=4)e.push(4294967296*p.random()|0);return o.create(e,a)}}),m=i.enc={},s=m.Hex={stringify:function(a){for(var e=a.words,a=a.sigBytes,c=[],b=0;b<a;b++){var d=e[b>>>2]>>>24-8*(b%4)&255;c.push((d>>>4).toString(16));c.push((d&15).toString(16))}return c.join("")},parse:function(a){for(var e=a.length,c=[],b=0;b<e;b+=2)c[b>>>3]|=parseInt(a.substr(b,2),16)<<24-4*(b%8);return o.create(c,e/2)}},n=m.Latin1={stringify:function(a){for(var e=
    a.words,a=a.sigBytes,c=[],b=0;b<a;b++)c.push(String.fromCharCode(e[b>>>2]>>>24-8*(b%4)&255));return c.join("")},parse:function(a){for(var e=a.length,c=[],b=0;b<e;b++)c[b>>>2]|=(a.charCodeAt(b)&255)<<24-8*(b%4);return o.create(c,e)}},k=m.Utf8={stringify:function(a){try{return decodeURIComponent(escape(n.stringify(a)))}catch(e){throw Error("Malformed UTF-8 data");}},parse:function(a){return n.parse(unescape(encodeURIComponent(a)))}},f=l.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=o.create();
    this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=k.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var e=this._data,c=e.words,b=e.sigBytes,d=this.blockSize,q=b/(4*d),q=a?p.ceil(q):p.max((q|0)-this._minBufferSize,0),a=q*d,b=p.min(4*a,b);if(a){for(var j=0;j<a;j+=d)this._doProcessBlock(c,j);j=c.splice(0,a);e.sigBytes-=b}return o.create(j,b)},clone:function(){var a=r.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});l.Hasher=f.extend({init:function(){this.reset()},
    reset:function(){f.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);this._doFinalize();return this._hash},clone:function(){var a=f.clone.call(this);a._hash=this._hash.clone();return a},blockSize:16,_createHelper:function(a){return function(e,c){return a.create(c).finalize(e)}},_createHmacHelper:function(a){return function(e,c){return g.HMAC.create(a,c).finalize(e)}}});var g=i.algo={};return i}(Math);
    (function(){var p=CryptoJS,h=p.lib.WordArray;p.enc.Base64={stringify:function(i){var l=i.words,h=i.sigBytes,o=this._map;i.clamp();for(var i=[],m=0;m<h;m+=3)for(var s=(l[m>>>2]>>>24-8*(m%4)&255)<<16|(l[m+1>>>2]>>>24-8*((m+1)%4)&255)<<8|l[m+2>>>2]>>>24-8*((m+2)%4)&255,n=0;4>n&&m+0.75*n<h;n++)i.push(o.charAt(s>>>6*(3-n)&63));if(l=o.charAt(64))for(;i.length%4;)i.push(l);return i.join("")},parse:function(i){var i=i.replace(/\s/g,""),l=i.length,r=this._map,o=r.charAt(64);o&&(o=i.indexOf(o),-1!=o&&(l=o));
    for(var o=[],m=0,s=0;s<l;s++)if(s%4){var n=r.indexOf(i.charAt(s-1))<<2*(s%4),k=r.indexOf(i.charAt(s))>>>6-2*(s%4);o[m>>>2]|=(n|k)<<24-8*(m%4);m++}return h.create(o,m)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
    (function(p){function h(f,g,a,e,c,b,d){f=f+(g&a|~g&e)+c+d;return(f<<b|f>>>32-b)+g}function i(f,g,a,e,c,b,d){f=f+(g&e|a&~e)+c+d;return(f<<b|f>>>32-b)+g}function l(f,g,a,e,c,b,d){f=f+(g^a^e)+c+d;return(f<<b|f>>>32-b)+g}function r(f,g,a,e,c,b,d){f=f+(a^(g|~e))+c+d;return(f<<b|f>>>32-b)+g}var o=CryptoJS,m=o.lib,s=m.WordArray,m=m.Hasher,n=o.algo,k=[];(function(){for(var f=0;64>f;f++)k[f]=4294967296*p.abs(p.sin(f+1))|0})();n=n.MD5=m.extend({_doReset:function(){this._hash=s.create([1732584193,4023233417,
    2562383102,271733878])},_doProcessBlock:function(f,g){for(var a=0;16>a;a++){var e=g+a,c=f[e];f[e]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360}for(var e=this._hash.words,c=e[0],b=e[1],d=e[2],q=e[3],a=0;64>a;a+=4)16>a?(c=h(c,b,d,q,f[g+a],7,k[a]),q=h(q,c,b,d,f[g+a+1],12,k[a+1]),d=h(d,q,c,b,f[g+a+2],17,k[a+2]),b=h(b,d,q,c,f[g+a+3],22,k[a+3])):32>a?(c=i(c,b,d,q,f[g+(a+1)%16],5,k[a]),q=i(q,c,b,d,f[g+(a+6)%16],9,k[a+1]),d=i(d,q,c,b,f[g+(a+11)%16],14,k[a+2]),b=i(b,d,q,c,f[g+a%16],20,k[a+3])):48>a?(c=
    l(c,b,d,q,f[g+(3*a+5)%16],4,k[a]),q=l(q,c,b,d,f[g+(3*a+8)%16],11,k[a+1]),d=l(d,q,c,b,f[g+(3*a+11)%16],16,k[a+2]),b=l(b,d,q,c,f[g+(3*a+14)%16],23,k[a+3])):(c=r(c,b,d,q,f[g+3*a%16],6,k[a]),q=r(q,c,b,d,f[g+(3*a+7)%16],10,k[a+1]),d=r(d,q,c,b,f[g+(3*a+14)%16],15,k[a+2]),b=r(b,d,q,c,f[g+(3*a+5)%16],21,k[a+3]));e[0]=e[0]+c|0;e[1]=e[1]+b|0;e[2]=e[2]+d|0;e[3]=e[3]+q|0},_doFinalize:function(){var f=this._data,g=f.words,a=8*this._nDataBytes,e=8*f.sigBytes;g[e>>>5]|=128<<24-e%32;g[(e+64>>>9<<4)+14]=(a<<8|a>>>
    24)&16711935|(a<<24|a>>>8)&4278255360;f.sigBytes=4*(g.length+1);this._process();f=this._hash.words;for(g=0;4>g;g++)a=f[g],f[g]=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360}});o.MD5=m._createHelper(n);o.HmacMD5=m._createHmacHelper(n)})(Math);
    (function(){var p=CryptoJS,h=p.lib,i=h.Base,l=h.WordArray,h=p.algo,r=h.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:h.MD5,iterations:1}),init:function(i){this.cfg=this.cfg.extend(i)},compute:function(i,m){for(var h=this.cfg,n=h.hasher.create(),k=l.create(),f=k.words,g=h.keySize,h=h.iterations;f.length<g;){a&&n.update(a);var a=n.update(i).finalize(m);n.reset();for(var e=1;e<h;e++)a=n.finalize(a),n.reset();k.concat(a)}k.sigBytes=4*g;return k}});p.EvpKDF=function(i,l,h){return r.create(h).compute(i,
    l)}})();
    CryptoJS.lib.Cipher||function(p){var h=CryptoJS,i=h.lib,l=i.Base,r=i.WordArray,o=i.BufferedBlockAlgorithm,m=h.enc.Base64,s=h.algo.EvpKDF,n=i.Cipher=o.extend({cfg:l.extend(),createEncryptor:function(b,d){return this.create(this._ENC_XFORM_MODE,b,d)},createDecryptor:function(b,d){return this.create(this._DEC_XFORM_MODE,b,d)},init:function(b,d,a){this.cfg=this.cfg.extend(a);this._xformMode=b;this._key=d;this.reset()},reset:function(){o.reset.call(this);this._doReset()},process:function(b){this._append(b);return this._process()},
    finalize:function(b){b&&this._append(b);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){return function(b){return{encrypt:function(a,q,j){return("string"==typeof q?c:e).encrypt(b,a,q,j)},decrypt:function(a,q,j){return("string"==typeof q?c:e).decrypt(b,a,q,j)}}}}()});i.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var k=h.mode={},f=i.BlockCipherMode=l.extend({createEncryptor:function(b,a){return this.Encryptor.create(b,
    a)},createDecryptor:function(b,a){return this.Decryptor.create(b,a)},init:function(b,a){this._cipher=b;this._iv=a}}),k=k.CBC=function(){function b(b,a,d){var c=this._iv;c?this._iv=p:c=this._prevBlock;for(var e=0;e<d;e++)b[a+e]^=c[e]}var a=f.extend();a.Encryptor=a.extend({processBlock:function(a,d){var c=this._cipher,e=c.blockSize;b.call(this,a,d,e);c.encryptBlock(a,d);this._prevBlock=a.slice(d,d+e)}});a.Decryptor=a.extend({processBlock:function(a,d){var c=this._cipher,e=c.blockSize,f=a.slice(d,d+
    e);c.decryptBlock(a,d);b.call(this,a,d,e);this._prevBlock=f}});return a}(),g=(h.pad={}).Pkcs7={pad:function(b,a){for(var c=4*a,c=c-b.sigBytes%c,e=c<<24|c<<16|c<<8|c,f=[],g=0;g<c;g+=4)f.push(e);c=r.create(f,c);b.concat(c)},unpad:function(b){b.sigBytes-=b.words[b.sigBytes-1>>>2]&255}};i.BlockCipher=n.extend({cfg:n.cfg.extend({mode:k,padding:g}),reset:function(){n.reset.call(this);var b=this.cfg,a=b.iv,b=b.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=b.createEncryptor;else c=b.createDecryptor,
    this._minBufferSize=1;this._mode=c.call(b,this,a&&a.words)},_doProcessBlock:function(b,a){this._mode.processBlock(b,a)},_doFinalize:function(){var b=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){b.pad(this._data,this.blockSize);var a=this._process(!0)}else a=this._process(!0),b.unpad(a);return a},blockSize:4});var a=i.CipherParams=l.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),k=(h.format={}).OpenSSL={stringify:function(a){var d=
    a.ciphertext,a=a.salt,d=(a?r.create([1398893684,1701076831]).concat(a).concat(d):d).toString(m);return d=d.replace(/(.{64})/g,"$1\n")},parse:function(b){var b=m.parse(b),d=b.words;if(1398893684==d[0]&&1701076831==d[1]){var c=r.create(d.slice(2,4));d.splice(0,4);b.sigBytes-=16}return a.create({ciphertext:b,salt:c})}},e=i.SerializableCipher=l.extend({cfg:l.extend({format:k}),encrypt:function(b,d,c,e){var e=this.cfg.extend(e),f=b.createEncryptor(c,e),d=f.finalize(d),f=f.cfg;return a.create({ciphertext:d,
    key:c,iv:f.iv,algorithm:b,mode:f.mode,padding:f.padding,blockSize:b.blockSize,formatter:e.format})},decrypt:function(a,c,e,f){f=this.cfg.extend(f);c=this._parse(c,f.format);return a.createDecryptor(e,f).finalize(c.ciphertext)},_parse:function(a,c){return"string"==typeof a?c.parse(a):a}}),h=(h.kdf={}).OpenSSL={compute:function(b,c,e,f){f||(f=r.random(8));b=s.create({keySize:c+e}).compute(b,f);e=r.create(b.words.slice(c),4*e);b.sigBytes=4*c;return a.create({key:b,iv:e,salt:f})}},c=i.PasswordBasedCipher=
    e.extend({cfg:e.cfg.extend({kdf:h}),encrypt:function(a,c,f,j){j=this.cfg.extend(j);f=j.kdf.compute(f,a.keySize,a.ivSize);j.iv=f.iv;a=e.encrypt.call(this,a,c,f.key,j);a.mixIn(f);return a},decrypt:function(a,c,f,j){j=this.cfg.extend(j);c=this._parse(c,j.format);f=j.kdf.compute(f,a.keySize,a.ivSize,c.salt);j.iv=f.iv;return e.decrypt.call(this,a,c,f.key,j)}})}();
    (function(){var p=CryptoJS,h=p.lib.BlockCipher,i=p.algo,l=[],r=[],o=[],m=[],s=[],n=[],k=[],f=[],g=[],a=[];(function(){for(var c=[],b=0;256>b;b++)c[b]=128>b?b<<1:b<<1^283;for(var d=0,e=0,b=0;256>b;b++){var j=e^e<<1^e<<2^e<<3^e<<4,j=j>>>8^j&255^99;l[d]=j;r[j]=d;var i=c[d],h=c[i],p=c[h],t=257*c[j]^16843008*j;o[d]=t<<24|t>>>8;m[d]=t<<16|t>>>16;s[d]=t<<8|t>>>24;n[d]=t;t=16843009*p^65537*h^257*i^16843008*d;k[j]=t<<24|t>>>8;f[j]=t<<16|t>>>16;g[j]=t<<8|t>>>24;a[j]=t;d?(d=i^c[c[c[p^i]]],e^=c[c[e]]):d=e=1}})();
    var e=[0,1,2,4,8,16,32,64,128,27,54],i=i.AES=h.extend({_doReset:function(){for(var c=this._key,b=c.words,d=c.sigBytes/4,c=4*((this._nRounds=d+6)+1),i=this._keySchedule=[],j=0;j<c;j++)if(j<d)i[j]=b[j];else{var h=i[j-1];j%d?6<d&&4==j%d&&(h=l[h>>>24]<<24|l[h>>>16&255]<<16|l[h>>>8&255]<<8|l[h&255]):(h=h<<8|h>>>24,h=l[h>>>24]<<24|l[h>>>16&255]<<16|l[h>>>8&255]<<8|l[h&255],h^=e[j/d|0]<<24);i[j]=i[j-d]^h}b=this._invKeySchedule=[];for(d=0;d<c;d++)j=c-d,h=d%4?i[j]:i[j-4],b[d]=4>d||4>=j?h:k[l[h>>>24]]^f[l[h>>>
    16&255]]^g[l[h>>>8&255]]^a[l[h&255]]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,o,m,s,n,l)},decryptBlock:function(c,b){var d=c[b+1];c[b+1]=c[b+3];c[b+3]=d;this._doCryptBlock(c,b,this._invKeySchedule,k,f,g,a,r);d=c[b+1];c[b+1]=c[b+3];c[b+3]=d},_doCryptBlock:function(a,b,d,e,f,h,i,g){for(var l=this._nRounds,k=a[b]^d[0],m=a[b+1]^d[1],o=a[b+2]^d[2],n=a[b+3]^d[3],p=4,r=1;r<l;r++)var s=e[k>>>24]^f[m>>>16&255]^h[o>>>8&255]^i[n&255]^d[p++],u=e[m>>>24]^f[o>>>16&255]^h[n>>>8&255]^
    i[k&255]^d[p++],v=e[o>>>24]^f[n>>>16&255]^h[k>>>8&255]^i[m&255]^d[p++],n=e[n>>>24]^f[k>>>16&255]^h[m>>>8&255]^i[o&255]^d[p++],k=s,m=u,o=v;s=(g[k>>>24]<<24|g[m>>>16&255]<<16|g[o>>>8&255]<<8|g[n&255])^d[p++];u=(g[m>>>24]<<24|g[o>>>16&255]<<16|g[n>>>8&255]<<8|g[k&255])^d[p++];v=(g[o>>>24]<<24|g[n>>>16&255]<<16|g[k>>>8&255]<<8|g[m&255])^d[p++];n=(g[n>>>24]<<24|g[k>>>16&255]<<16|g[m>>>8&255]<<8|g[o&255])^d[p++];a[b]=s;a[b+1]=u;a[b+2]=v;a[b+3]=n},keySize:8});p.AES=h._createHelper(i)})();

    return {
       encrypt:function(data, password) { return CryptoJS.AES.encrypt(data, password); },
       decrypt:function(data, password) { return CryptoJS.AES.decrypt(data, password); }
   }
}

application.client.tools.crypto.rabbit = function(){
    /*
    CryptoJS v3.0.2
    code.google.com/p/crypto-js
    (c) 2009-2012 by Jeff Mott. All rights reserved.
    code.google.com/p/crypto-js/wiki/License
    */
    var CryptoJS=CryptoJS||function(n,l){var i={},j=i.lib={},k=j.Base=function(){function b(){}return{extend:function(p){b.prototype=this;var a=new b;p&&a.mixIn(p);a.$super=this;return a},create:function(){var b=this.extend();b.init.apply(b,arguments);return b},init:function(){},mixIn:function(b){for(var a in b)b.hasOwnProperty(a)&&(this[a]=b[a]);b.hasOwnProperty("toString")&&(this.toString=b.toString)},clone:function(){return this.$super.extend(this)}}}(),e=j.WordArray=k.extend({init:function(b,a){b=
    this.words=b||[];this.sigBytes=a!=l?a:4*b.length},toString:function(b){return(b||c).stringify(this)},concat:function(b){var a=this.words,c=b.words,g=this.sigBytes,b=b.sigBytes;this.clamp();if(g%4)for(var h=0;h<b;h++)a[g+h>>>2]|=(c[h>>>2]>>>24-8*(h%4)&255)<<24-8*((g+h)%4);else if(65535<c.length)for(h=0;h<b;h+=4)a[g+h>>>2]=c[h>>>2];else a.push.apply(a,c);this.sigBytes+=b;return this},clamp:function(){var b=this.words,a=this.sigBytes;b[a>>>2]&=4294967295<<32-8*(a%4);b.length=n.ceil(a/4)},clone:function(){var b=
    k.clone.call(this);b.words=this.words.slice(0);return b},random:function(b){for(var a=[],c=0;c<b;c+=4)a.push(4294967296*n.random()|0);return e.create(a,b)}}),d=i.enc={},c=d.Hex={stringify:function(b){for(var a=b.words,b=b.sigBytes,c=[],g=0;g<b;g++){var h=a[g>>>2]>>>24-8*(g%4)&255;c.push((h>>>4).toString(16));c.push((h&15).toString(16))}return c.join("")},parse:function(b){for(var a=b.length,c=[],g=0;g<a;g+=2)c[g>>>3]|=parseInt(b.substr(g,2),16)<<24-4*(g%8);return e.create(c,a/2)}},a=d.Latin1={stringify:function(b){for(var a=
    b.words,b=b.sigBytes,c=[],g=0;g<b;g++)c.push(String.fromCharCode(a[g>>>2]>>>24-8*(g%4)&255));return c.join("")},parse:function(b){for(var a=b.length,c=[],g=0;g<a;g++)c[g>>>2]|=(b.charCodeAt(g)&255)<<24-8*(g%4);return e.create(c,a)}},f=d.Utf8={stringify:function(b){try{return decodeURIComponent(escape(a.stringify(b)))}catch(c){throw Error("Malformed UTF-8 data");}},parse:function(b){return a.parse(unescape(encodeURIComponent(b)))}},o=j.BufferedBlockAlgorithm=k.extend({reset:function(){this._data=e.create();
    this._nDataBytes=0},_append:function(b){"string"==typeof b&&(b=f.parse(b));this._data.concat(b);this._nDataBytes+=b.sigBytes},_process:function(b){var a=this._data,c=a.words,g=a.sigBytes,h=this.blockSize,m=g/(4*h),m=b?n.ceil(m):n.max((m|0)-this._minBufferSize,0),b=m*h,g=n.min(4*b,g);if(b){for(var o=0;o<b;o+=h)this._doProcessBlock(c,o);o=c.splice(0,b);a.sigBytes-=g}return e.create(o,g)},clone:function(){var b=k.clone.call(this);b._data=this._data.clone();return b},_minBufferSize:0});j.Hasher=o.extend({init:function(){this.reset()},
    reset:function(){o.reset.call(this);this._doReset()},update:function(b){this._append(b);this._process();return this},finalize:function(b){b&&this._append(b);this._doFinalize();return this._hash},clone:function(){var b=o.clone.call(this);b._hash=this._hash.clone();return b},blockSize:16,_createHelper:function(b){return function(a,c){return b.create(c).finalize(a)}},_createHmacHelper:function(b){return function(a,c){return q.HMAC.create(b,c).finalize(a)}}});var q=i.algo={};return i}(Math);
    (function(){var n=CryptoJS,l=n.lib.WordArray;n.enc.Base64={stringify:function(i){var j=i.words,k=i.sigBytes,e=this._map;i.clamp();for(var i=[],d=0;d<k;d+=3)for(var c=(j[d>>>2]>>>24-8*(d%4)&255)<<16|(j[d+1>>>2]>>>24-8*((d+1)%4)&255)<<8|j[d+2>>>2]>>>24-8*((d+2)%4)&255,a=0;4>a&&d+0.75*a<k;a++)i.push(e.charAt(c>>>6*(3-a)&63));if(j=e.charAt(64))for(;i.length%4;)i.push(j);return i.join("")},parse:function(i){var i=i.replace(/\s/g,""),j=i.length,k=this._map,e=k.charAt(64);e&&(e=i.indexOf(e),-1!=e&&(j=e));
    for(var e=[],d=0,c=0;c<j;c++)if(c%4){var a=k.indexOf(i.charAt(c-1))<<2*(c%4),f=k.indexOf(i.charAt(c))>>>6-2*(c%4);e[d>>>2]|=(a|f)<<24-8*(d%4);d++}return l.create(e,d)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
    (function(n){function l(a,c,b,d,f,g,h){a=a+(c&b|~c&d)+f+h;return(a<<g|a>>>32-g)+c}function i(a,c,b,d,f,g,h){a=a+(c&d|b&~d)+f+h;return(a<<g|a>>>32-g)+c}function j(a,c,b,d,f,g,h){a=a+(c^b^d)+f+h;return(a<<g|a>>>32-g)+c}function k(a,c,b,d,f,g,h){a=a+(b^(c|~d))+f+h;return(a<<g|a>>>32-g)+c}var e=CryptoJS,d=e.lib,c=d.WordArray,d=d.Hasher,a=e.algo,f=[];(function(){for(var a=0;64>a;a++)f[a]=4294967296*n.abs(n.sin(a+1))|0})();a=a.MD5=d.extend({_doReset:function(){this._hash=c.create([1732584193,4023233417,
    2562383102,271733878])},_doProcessBlock:function(a,c){for(var b=0;16>b;b++){var d=c+b,e=a[d];a[d]=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360}for(var d=this._hash.words,e=d[0],g=d[1],h=d[2],m=d[3],b=0;64>b;b+=4)16>b?(e=l(e,g,h,m,a[c+b],7,f[b]),m=l(m,e,g,h,a[c+b+1],12,f[b+1]),h=l(h,m,e,g,a[c+b+2],17,f[b+2]),g=l(g,h,m,e,a[c+b+3],22,f[b+3])):32>b?(e=i(e,g,h,m,a[c+(b+1)%16],5,f[b]),m=i(m,e,g,h,a[c+(b+6)%16],9,f[b+1]),h=i(h,m,e,g,a[c+(b+11)%16],14,f[b+2]),g=i(g,h,m,e,a[c+b%16],20,f[b+3])):48>b?(e=
    j(e,g,h,m,a[c+(3*b+5)%16],4,f[b]),m=j(m,e,g,h,a[c+(3*b+8)%16],11,f[b+1]),h=j(h,m,e,g,a[c+(3*b+11)%16],16,f[b+2]),g=j(g,h,m,e,a[c+(3*b+14)%16],23,f[b+3])):(e=k(e,g,h,m,a[c+3*b%16],6,f[b]),m=k(m,e,g,h,a[c+(3*b+7)%16],10,f[b+1]),h=k(h,m,e,g,a[c+(3*b+14)%16],15,f[b+2]),g=k(g,h,m,e,a[c+(3*b+5)%16],21,f[b+3]));d[0]=d[0]+e|0;d[1]=d[1]+g|0;d[2]=d[2]+h|0;d[3]=d[3]+m|0},_doFinalize:function(){var a=this._data,c=a.words,b=8*this._nDataBytes,d=8*a.sigBytes;c[d>>>5]|=128<<24-d%32;c[(d+64>>>9<<4)+14]=(b<<8|b>>>
    24)&16711935|(b<<24|b>>>8)&4278255360;a.sigBytes=4*(c.length+1);this._process();a=this._hash.words;for(c=0;4>c;c++)b=a[c],a[c]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360}});e.MD5=d._createHelper(a);e.HmacMD5=d._createHmacHelper(a)})(Math);
    (function(){var n=CryptoJS,l=n.lib,i=l.Base,j=l.WordArray,l=n.algo,k=l.EvpKDF=i.extend({cfg:i.extend({keySize:4,hasher:l.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,d){for(var c=this.cfg,a=c.hasher.create(),f=j.create(),i=f.words,k=c.keySize,c=c.iterations;i.length<k;){b&&a.update(b);var b=a.update(e).finalize(d);a.reset();for(var l=1;l<c;l++)b=a.finalize(b),a.reset();f.concat(b)}f.sigBytes=4*k;return f}});n.EvpKDF=function(e,d,c){return k.create(c).compute(e,
    d)}})();
    CryptoJS.lib.Cipher||function(n){var l=CryptoJS,i=l.lib,j=i.Base,k=i.WordArray,e=i.BufferedBlockAlgorithm,d=l.enc.Base64,c=l.algo.EvpKDF,a=i.Cipher=e.extend({cfg:j.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=b;this.reset()},reset:function(){e.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()},
    finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){return function(a){return{encrypt:function(b,c,d){return("string"==typeof c?r:p).encrypt(a,b,c,d)},decrypt:function(b,c,d){return("string"==typeof c?r:p).decrypt(a,b,c,d)}}}}()});i.StreamCipher=a.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var f=l.mode={},o=i.BlockCipherMode=j.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,
    b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a;this._iv=b}}),f=f.CBC=function(){function a(b,c,g){var d=this._iv;d?this._iv=n:d=this._prevBlock;for(var h=0;h<g;h++)b[c+h]^=d[h]}var b=o.extend();b.Encryptor=b.extend({processBlock:function(b,c){var d=this._cipher,h=d.blockSize;a.call(this,b,c,h);d.encryptBlock(b,c);this._prevBlock=b.slice(c,c+h)}});b.Decryptor=b.extend({processBlock:function(b,c){var d=this._cipher,h=d.blockSize,f=b.slice(c,c+
    h);d.decryptBlock(b,c);a.call(this,b,c,h);this._prevBlock=f}});return b}(),q=(l.pad={}).Pkcs7={pad:function(a,b){for(var c=4*b,c=c-a.sigBytes%c,d=c<<24|c<<16|c<<8|c,f=[],e=0;e<c;e+=4)f.push(d);c=k.create(f,c);a.concat(c)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};i.BlockCipher=a.extend({cfg:a.cfg.extend({mode:f,padding:q}),reset:function(){a.reset.call(this);var b=this.cfg,c=b.iv,b=b.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=b.createEncryptor;else d=b.createDecryptor,
    this._minBufferSize=1;this._mode=d.call(b,this,c&&c.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var b=i.CipherParams=j.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),f=(l.format={}).OpenSSL={stringify:function(a){var b=
    a.ciphertext,a=a.salt,b=(a?k.create([1398893684,1701076831]).concat(a).concat(b):b).toString(d);return b=b.replace(/(.{64})/g,"$1\n")},parse:function(a){var a=d.parse(a),c=a.words;if(1398893684==c[0]&&1701076831==c[1]){var f=k.create(c.slice(2,4));c.splice(0,4);a.sigBytes-=16}return b.create({ciphertext:a,salt:f})}},p=i.SerializableCipher=j.extend({cfg:j.extend({format:f}),encrypt:function(a,c,d,f){var f=this.cfg.extend(f),e=a.createEncryptor(d,f),c=e.finalize(c),e=e.cfg;return b.create({ciphertext:c,
    key:d,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding,blockSize:a.blockSize,formatter:f.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a):a}}),l=(l.kdf={}).OpenSSL={compute:function(a,d,f,e){e||(e=k.random(8));a=c.create({keySize:d+f}).compute(a,e);f=k.create(a.words.slice(d),4*f);a.sigBytes=4*d;return b.create({key:a,iv:f,salt:e})}},r=i.PasswordBasedCipher=
    p.extend({cfg:p.cfg.extend({kdf:l}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);c=d.kdf.compute(c,a.keySize,a.ivSize);d.iv=c.iv;a=p.encrypt.call(this,a,b,c.key,d);a.mixIn(c);return a},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);c=d.kdf.compute(c,a.keySize,a.ivSize,b.salt);d.iv=c.iv;return p.decrypt.call(this,a,b,c.key,d)}})}();
    (function(){function n(){var d=this._X,c=this._C;c[0]=c[0]+1295307597+this._b|0;c[1]=c[1]+3545052371+(1295307597>c[0]>>>0?1:0)|0;c[2]=c[2]+886263092+(3545052371>c[1]>>>0?1:0)|0;c[3]=c[3]+1295307597+(886263092>c[2]>>>0?1:0)|0;c[4]=c[4]+3545052371+(1295307597>c[3]>>>0?1:0)|0;c[5]=c[5]+886263092+(3545052371>c[4]>>>0?1:0)|0;c[6]=c[6]+1295307597+(886263092>c[5]>>>0?1:0)|0;c[7]=c[7]+3545052371+(1295307597>c[6]>>>0?1:0)|0;this._b=3545052371>c[7]>>>0?1:0;for(var a=0;8>a;a++){var f=d[a]+c[a],e=f&65535,i=f>>>
    16;k[a]=((e*e>>>17)+e*i>>>15)+i*i^((f&4294901760)*f|0)+((f&65535)*f|0)}var c=k[0],a=k[1],f=k[2],e=k[3],i=k[4],b=k[5],j=k[6],l=k[7];d[0]=c+(l<<16|l>>>16)+(j<<16|j>>>16)|0;d[1]=a+(c<<8|c>>>24)+l|0;d[2]=f+(a<<16|a>>>16)+(c<<16|c>>>16)|0;d[3]=e+(f<<8|f>>>24)+a|0;d[4]=i+(e<<16|e>>>16)+(f<<16|f>>>16)|0;d[5]=b+(i<<8|i>>>24)+e|0;d[6]=j+(b<<16|b>>>16)+(i<<16|i>>>16)|0;d[7]=l+(j<<8|j>>>24)+b|0}var l=CryptoJS,i=l.lib.StreamCipher,j=[],k=[],e=l.algo.Rabbit=i.extend({_doReset:function(){for(var d=this._key.words,
    c=d[0],a=d[1],f=d[2],e=d[3],d=this._X=[c,e<<16|f>>>16,a,c<<16|e>>>16,f,a<<16|c>>>16,e,f<<16|a>>>16],c=this._C=[f<<16|f>>>16,c&4294901760|a&65535,e<<16|e>>>16,a&4294901760|f&65535,c<<16|c>>>16,f&4294901760|e&65535,a<<16|a>>>16,e&4294901760|c&65535],a=this._b=0;4>a;a++)n.call(this);for(a=0;8>a;a++)c[a]^=d[a+4&7];if(d=this.cfg.iv){a=d.words;d=a[0];a=a[1];d=(d<<8|d>>>24)&16711935|(d<<24|d>>>8)&4278255360;a=(a<<8|a>>>24)&16711935|(a<<24|a>>>8)&4278255360;f=d>>>16|a&4294901760;e=a<<16|d&65535;c[0]^=d;c[1]^=
    f;c[2]^=a;c[3]^=e;c[4]^=d;c[5]^=f;c[6]^=a;c[7]^=e;for(a=0;4>a;a++)n.call(this)}},_doProcessBlock:function(d,c){var a=this._X;n.call(this);j[0]=a[0]^a[5]>>>16^a[3]<<16;j[1]=a[2]^a[7]>>>16^a[5]<<16;j[2]=a[4]^a[1]>>>16^a[7]<<16;j[3]=a[6]^a[3]>>>16^a[1]<<16;for(a=0;4>a;a++){var e=j[a],e=(e<<8|e>>>24)&16711935|(e<<24|e>>>8)&4278255360;d[c+a]^=e}},blockSize:4,ivSize:2});l.Rabbit=i._createHelper(e)})();

    return {
       encrypt:function(data, password) { return CryptoJS.Rabbit.encrypt(data, password); },
       decrypt:function(data, password) { return CryptoJS.Rabbit.decrypt(data, password); }
   }
    
}


















/**
 *
 * jQuery plugin to impliment RSA public key encryption for
 * form submissions.
 *
 * Utilizes the pidCrypt libraries for client public key
 * encryption while the associated PHP class uses
 * OpenSSL to generate the necessary private/public key pairs used
 * by this plug-in
 *
 * Fork me @ https://www.github.com/jas-/jQuery.pidCrypt
 *
 * Author: Jason Gerfen <jason.gerfen@gmail.com>
 * License: GPL (see LICENSE)
 *
 */

(function($){

 /**
  * @function jQuery.pidCrypt
  * @abstract Plug-in to implement pidCrypt RSA and AES
  *           encryption for public key encryption of
  *           web form elements with support for
  *           client storage options
  * @param method string Method to employ for form ID DOM object
  *                      default, sign, verify, encrypt_sign,
  *                      decrypt_verify, authenticate
  * @param options object options object for specific operations
  *                       cache, debug, callback
  */
 $.fn.pidCrypt = function(method) {

  /**
   * @object defaults
   * @abstract Default set of options for plug-in
   */
  var defaults = defaults || {
   appID:        '',                   // Configurable CSRF token
   storage:      'session',            // Configurable storage mechanism
   formID:       $(this),              // Global object for bound DOM object
   type:         'json',               // Configurable method of communication
   aes:          '',                   // Global object for AES encryption key
   keys:         {},                   // Global object for client keyring
   use:          '',                   // Global object for client public key
   callback:     function(){},         // Configurable callback method on XMLHttpRequest success
   preCallback:  function(){},         // Configurable callback prior to XMLHttpRequest
   errCallback:  function(){}          // Configurable callback on XMLHttpRequest error
  };

  /**
   * @object methods
   * @abstract Plug-in methods
   */
  var methods = methods || {

   /**
    * @function init
    * @abstract Default plug-in method. Requests public key, optionally
    *           uses client storage for key, gathers non-null form elements,
    *           encrypts and sends to server for private key decryption
    */
   init: function(o){
    var opts = _main.__setup(o, defaults);
    $('body').removeData('use');
    _modal.__setup(opts);
    $('#keyring').change(function(){ $('body').data('use', _modal.__e(opts, $(this).val())); opts = _main.__setup(o, defaults); });
    $('#'+opts.formID.attr('id')).on('submit', function(e){
     e.preventDefault();
     _main.__do(opts, _main.__gF(opts));
    });
    return true;
   }
  };

  /**
   * @object main
   * @abstract Handles primary functions
   */
  var _main = _main || {

   /**
    * @object _do
    * @abstract Performs all AJAX requests. Sets additional CSRF and checksum
    *           header fields which can be verified on server
    */
   __do: function(o, a){
    var _data = (typeof a=='object') ? _strings.__serialize(a) : a;
    $.ajax({
     form: o.formID.attr('id'),
     url: o.formID.attr('action'),
     type: o.formID.attr('method'),
     data: _data,
     dataType: o.type,
     crossDomain: (o.type==='jsonp') ? true : false,
     beforeSend: function(xhr){
      xhr = _main.__sH(o, xhr, _data);
      ((o.preCallback)&&($.isFunction(o.preCallback))) ? o.preCallback(xhr) : false;
     },
     success: function(x, status, xhr){
      (x) ? _keys.__hR(x, o) : false;
      ((o.callback)&&($.isFunction(o.callback))) ? o.callback.call(x) : console.log(x);
     },
     error: function(xhr, status, error){
      ((o.errCallback)&&($.isFunction(o.errCallback))) ? o.errCallback.call(xhr, status, error) : false;
     }
    });
   },

   /**
    * @function __setup
    * @abstract Performs simple global setup functions
    */
   __setup: function(o, d){
    var opts = $.extend({}, d, o);
    opts.aes = _encrypt.__sAES();
    opts.keys = _keys.__existing(opts);
    opts.appID = (_validation.__vStr(opts.appID)) ? opts.appID : _keys.__gUUID(null);
    if (_validation.__szCk(opts.keys)<=0){
     _keys.__hK(opts);
    }
    opts.use = ($('body').data('use')) ? $('body').data('use') : _keys.__sK(opts);
    return opts;
   },

   /**
    * @function __gF
    * @abstract Performs object creation of non-null form elements
    */
   __gF: function(o){
    var obj={};
    if (!_validation.__vStr(o.use)) {
     o = _main.__setup(o, defaults);
    }
    $.each($('#'+o.formID.attr('id')+' :input, input:radio:selected, input:checkbox:checked, textarea'), function(k, v){
     if ((_validation.__vStr(v.value))&&(_validation.__vStr(v.name))){
      obj[v.name] = (parseInt(v.value.length)>80) ? _strings.__sSplt(v.value) : v.value;
     }
    });
    return _encrypt.__eO(o, obj);
   },

   /**
    * @function __sH
    * @abstract Sets application specific header options
    */
   __sH: function(o, xhr, _data){
    xhr.setRequestHeader('X-Alt-Referer', o.appID);
    if (_validation.__vStr(_keys.__gT(document.cookie))){
     xhr.setRequestHeader("X-Token",_keys.__gT(document.cookie));
    }
    if (_validation.__vStr(_data)){
     xhr.setRequestHeader('Content-MD5', pidCryptUtil.encodeBase64(pidCrypt.MD5(_data)));
    } else {
     xhr.setRequestHeader('Content-MD5', pidCryptUtil.encodeBase64(pidCrypt.MD5(o.appID)));
    }
    if (!_data){
     xhr.setRequestHeader('Access-Control-Allow-Origin', _keys.__id());
     xhr.setRequestHeader('Access-Control-Allow-Methods', 'POST');
     xhr.setRequestHeader('Content-Type', 'application/json');
    }
    return xhr;
   }
  }

  /**
   * @object keys
   * @abstract Object providing interface for key retrieval and storage
   */
  var _keys = _keys || {

   /**
    * @function __hK
    * @abstract Handles retrieval, encryption and storage of key
    */
   __hK: function(o){
    var y = function(){
     var z = (this) ? this : false;
     var email = ((z)&&(z.email)) ? z.email : o.appID;
     var key = ((z)&&(z.key)) ? z.key : false;
     if (!key) return false;
     var obj = {}; obj[o.appID] = {};
     obj[o.appID]['email'] = _encrypt.__e(o.aes, email, o.appID);
     obj[o.appID]['key'] = _encrypt.__e(o.aes, key, o.appID);
     obj = $.extend({}, obj, _keys.__existing(o));
     _storage.__sI(o.storage, _keys.__id(), JSON.stringify(obj));
    }
    o.callback = y;
    _main.__do(o, {'key': true});
    return true;
   },

   /**
    * @function __sK
    * @abstract Attempts to find email address for user specific key retrieval
    */
   __sK: function(o){
    var _r = false;
    if (_validation.__szCk(o.keys)>0){
     $.each(o.keys, function(a,b){
      var _x = /[0-9a-z-_.]{2,45}\@[0-9a-z-_.]{2,45}\.[a-z]{2,4}/i;
      var _e = _encrypt.__d(o.aes, b['email'], a);
      if (_x.test(_e)){
       _r = _encrypt.__d(o.aes, b['key'], a);
       return false;
      } else {
       _r = _encrypt.__d(o.aes, b['key'], a);
      }
     });
    }
    return _r;
   },

   /**
    * @function existing
    * @abstract Function used to return configured options
    *           as JSON object
    */
   __existing: function(o){
    return (_storage.__gI(o.storage, _keys.__id())) ? JSON.parse(_storage.__gI(o.storage, _keys.__id())) : false;
   },

   /**
    * @function __id
    * @abstract Need an id to associate the public key and other
    *           configuration options with a hostname or url
    */
   __id: function(){
    return (_validation.__vStr(location.host)) ? location.host : (_validation.__vStr(location.hostname)) ? location.hostname : 'localhost';
   },

   /**
    * @function gUUID
    * @abstract Generate a uuid (RFC-4122) string or optional hex
    *           string of specified length
    */
   __gUUID: function(len){
    var chars = '0123456789abcdef'.split('');
    var uuid = [], rnd = Math.random, r;
    uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
    uuid[14] = '4';
    for (var i = 0; i < 36; i++){
     if (!uuid[i]){
      r = 0 | rnd()*16;
      uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r & 0xf];
     }
    }
    return (len!==null) ? uuid.join('').replace(/-/g, '').split('',len).join('') : uuid.join('');
   },

   /**
    * @function strIV
    * @abstract Generate IV from string
    */
   __strIV: function(s){
    return (s) ? encodeURI(s.replace(/-/gi, '').substring(16,Math.ceil(16*s.length)%s.length)) : false;
   },

   /**
    * @function __hR
    * @abstract Searches response for new keyring data if any
    */
   __hR: function(r, o){
    var x = false;
    if (_validation.__szCk(r)>0){
     $.each(r, function(a, b){
      if ((a==='keyring')&&(_validation.__vStr(b['email']))){
       if(!_keys.__hlpr(o, b['email'])){
        var k = _keys.__gUUID(null); var obj = {}; obj[k] = {};
        obj[k]['email'] = _encrypt.__e(o.aes, b['email'], k);
        obj[k]['key'] = _encrypt.__e(o.aes, b['key'], k);
        obj = $.extend({}, obj, _keys.__existing(o));
        _storage.__sI(o.storage, _keys.__id(), JSON.stringify(obj));
       }
      }
     });
    }
    return x;
   },

   /**
    * @function __hlpr
    * @abstract Performs comparison on existing keyring entries for specified
    *           email address
    */
   __hlpr: function(o, e){
    var _r = false;
    $.each(_keys.__existing(o), function(a, b){
     if (_encrypt.__d(o.aes, b['email'], a)==e){
      _r = true;
     }
    });
    return _r;
   },

   /**
    * @function __gT
    * @abstract Obtains authentication token from cookie if it exists
    */
   __gT: function(c){
    var _r=false; var _c = c.split(';');
    $.each(_c, function(a, b){
     if (b.match('token=')){
      _r=b.substr(b.indexOf('=')+1);
     }
    });
    return _r;
   }
  }

  /**
   * @object encrypt
   * @abstract Handles encryption functionality
   */
  var _encrypt = _encrypt || {

   /**
    * @function eO
    * @abstract Calls certParser() on public key, intializes results with
    *           external pidCrypt.RSA object, performs public key encryption
    *           on object and returns results as object
    */
   __eO: function(o, obj){
    var x = {}; var y = _encrypt.__certParser(o.use);
    _encrypt.__iP(y);
    if (_validation.__szCk(obj)>0){
     $.each(obj, function(a, b){
      if (typeof b==='object'){
       x[a]={};
       $.each(b, function(k, v){
        x[a][k] = pidCrypt.RSA.prototype.encrypt(v);
       });
      } else {
       x[a] = pidCrypt.RSA.prototype.encrypt(b);
      }
     });
    } else {
     x = 0;
    }
    return x;
   },

   /**
    * @function sAES
    * @abstract Returns pidCrypt.AES.CBC object for client AES storage
    */
   __sAES: function(){
    return new pidCrypt.AES.CBC();
   },

   /**
    * @function iP
    * @abstract Returns external pidCrypt.RSA object once certParse()
    *           generates necessary bytes from public key
    */
   __iP: function(pub){
    var rsa = false;
    if (pub.b64){
     var x = pidCryptUtil.decodeBase64(pub.b64);
     rsa = new pidCrypt();
     var asn = pidCrypt.ASN1.decode(pidCryptUtil.toByteArray(x));
     var tree = asn.toHexTree();
     pidCrypt.RSA.prototype.setPublicKeyFromASN(tree);
    }
    return rsa;
   },

   /*
    * parse public/private key function
    * (Copyright https://www.pidder.com/pidcrypt/?page=demo_rsa-encryption)
    */
   __certParser: function(cert){
    if (!cert) return false;
    var lines = cert.split('\n');
    var read = false;
    var b64 = false;
    var end = false;
    var flag = '';
    var retObj = {};
    retObj.info = '';
    retObj.salt = '';
    retObj.iv;
    retObj.b64 = '';
    retObj.aes = false;
    retObj.mode = '';
    retObj.bits = 0;
    for(var i=0; i< lines.length; i++){
     flag = lines[i].substr(0,9);
     if(i==1 && flag != 'Proc-Type' && flag.indexOf('M') == 0)//unencrypted cert?
     b64 = true;
     switch(flag){
      case '-----BEGI':
       read = true;
       break;
      case 'Proc-Type':
       if(read)
        retObj.info = lines[i];
        break;
      case 'DEK-Info:':
       if(read){
        var tmp = lines[i].split(',');
        var dek = tmp[0].split(': ');
        var aes = dek[1].split('-');
        retObj.aes = (aes[0] == 'AES')?true:false;
        retObj.mode = aes[2];
        retObj.bits = parseInt(aes[1]);
        retObj.salt = tmp[1].substr(0,16);
        retObj.iv = tmp[1];
       }
       break;
      case '':
       if(read)
        b64 = true;
        break;
      case '-----END ':
       if(read){
        b64 = false;
        read = false;
       }
       break;
      default:
       if(read && b64)
        retObj.b64 += pidCryptUtil.stripLineFeeds(lines[i]);
     }
    }
    return retObj;
   },

   /**
    * @function __e
    * @abstract Encrypts specified string with specified pass & salt
    */
   __e: function(o, d, p){
    return encodeURI(o.encryptText(d, pidCrypt.SHA512(p), {nBits:256, salt:_keys.__strIV(pidCrypt.SHA512(p))}));
   },

   /**
    * @function __d
    * @abstract Decrypts specified string with specified pass & salt
    */
   __d: function(o, d, p){
    return decodeURI(o.decryptText(d, pidCrypt.SHA512(p), {nBits:256, salt:_keys.__strIV(pidCrypt.SHA512(p))}));
   }
  }

  /**
   * @object strings
   * @abstract Handles string processing
   */
  var _strings = _strings || {

   /**
    * @function _serialize
    * @abstract Create serialized string of object
    */
   __serialize: function(args){
    if (_validation.__szCk(args)>0){
     var x='';
     $.each(args, function(a, b){
      if (typeof b==='object'){
       $.each(b, function(c, d){
        x+=a+'['+c+']'+'='+d+'&';
       });
      } else {
       x+=a+'='+b+'&';
      }
     });
     x = x.substring(0, x.length-1);
    } else {
     return false;
    }
    return x;
   },

   /**
    * @function sSplt
    * @abstract Splits string length helper to overcome limitations with RSA
    *           cipher and key sizes
    */
   __sSplt: function(str){
    var t = str.length/80;
    var y = {}; var x=0; var z=80;
    for (var i=0; i<t; i++) {
     if (i>0) { x=x+80; z=z+80; }
     if (str.slice(x, z).length>0) {
      y[i] = str.slice(x, z);
     }
    }
    return y;
   }
  }

  /**
   * @object storage
   * @abstract Object to provide interface to key storage options
   */
  var _storage = _storage || {

   /**
    * @function sI
    * @abstract Proxy function for setting data with specified client storage
    *           option
    */
   __sI: function(type, k, v){
    var x = false;
    type = (_validation.__vStore(type+'Storage')) ? type : 'cookie';
    switch(type) {
     case 'local':
      x = this.__sL(k, v);
      break;
     case 'session':
      x = this.__sS(k, v);
      break;
     case 'cookie':
      x = this.__sC(k, v);
      break;
     default:
      x = this.__sL(k, v);
      break;
    }
    return x;
   },

   /**
    * @function gI
    * @abstract Proxy function for getting data with specified client storage
    *           option
    */
   __gI: function(type, k){
    var x = false;
    type = (_validation.__vStore(type+'Storage')) ? type : 'cookie';
    switch(type) {
     case 'local':
      x = this.__gL(k);
      break;
     case 'session':
      x = this.__gS(k);
      break;
     case 'cookie':
      x = this.__gC(k);
      break;
     default:
      x = this.__gL(k);
      break;
    }
    return x;
   },

   /**
    * @function dI
    * @abstract Proxy function for deleting data with specified client storage
    *           option
    */
   __dI: function(type, k){
    var x = false;
    type = (_validation.__vStore(type+'Storage')) ? type : 'cookie';
    switch(type) {
     case 'local':
      x = this.__dL(k);
      break;
     case 'session':
      x = this.__dS(k);
      break;
     case 'cookie':
      x = this.__dC(k);
      break;
     default:
      x = this.__dL(k);
      break;
    }
    return x;
   },

   /**
    * @function sL
    * @abstract Function used to set localStorage items
    */
   __sL: function(k, v){
    return (localStorage.setItem(k, v)) ? false : true;
   },

   /**
    * @function sS
    * @abstract Function used to set sessionStorage items
    */
   __sS: function(k, v){
    return (sessionStorage.setItem(k, v)) ? false : true;
   },

   /**
    * @function sC
    * @abstract Function used to set cookie items
    */
   __sC: function(k, v){
    if (typeof $.cookie === 'function') {
     return ($.cookie(k, v, {expires: 7})) ? true : false;
    } else {
     return false;
    }
   },

   /**
    * @function gL
    * @abstract Function used to get localStorage items
    */
   __gL: function(k){
    return (localStorage.getItem(k)) ? localStorage.getItem(k) : false;
   },

   /**
    * @function sS
    * @abstract Function used to get sessionStorage items
    */
   __gS: function(k){
    return (sessionStorage.getItem(k)) ? sessionStorage.getItem(k) : false;
   },

   /**
    * @function sC
    * @abstract Function used to get cookie items
    */
   __gC: function(name){
    if (typeof $.cookie === 'function') {
     return ($.cookie(name)) ? $.cookie(name) : false;
    } else {
     return false;
    }
   },

   /**
    * @function dL
    * @abstract Function used to delete localStorage items
    */
   __dL: function(k){
    return (localStorage.removeItem(k)) ? localStorage.removeItem(k) : false;
   },

   /**
    * @function dS
    * @abstract Function used to delete sessionStorage items
    */
   __dS: function(k){
    return (sessionStorage.removeItem(k)) ? sessionStorage.removeItem(k) : false;
   },

   /**
    * @function dC
    * @abstract Function used to delete cookie items
    */
   __dC: function(name){
    if (typeof $.cookie === 'function') {
     return ($.cookie(name, '', {expires: -7})) ? true : false;
    } else {
     return false;
    }
   }
  }

  /**
   * @method validation
   * @abstract Provides interface to validation functionality
   */
  var _validation = _validation || {

   /**
    * @function vStr
    * @abstract Function used combine string checking functions
    */
   __vStr: function(x){
    if (!x) return false;
    return ((x==false)||(x.length==0)||(!x)||(x==null)||(x=='')||(typeof x=='undefined')) ? false : true;
   },

   /**
    * @function vStore
    * @abstract Function used to validate client storage option
    */
   __vStore: function(type){
    try {
     return ((type in window)&&(window[type])) ? true : false;
    } catch (e) {
     return false;
    }
   },

   /**
    * @function szCk
    * @abstract Performs a check on object sizes
    */
   __szCk: function(obj){
    var n = 0;
    $.each(obj, function(k, v){
     if (obj.hasOwnProperty(k)) n++;
    });
    return n;
   }
  }

  /**
   * @method modal
   * @abstract Modal object
   */
  var _modal = _modal || {

   /**
    * @function __setup
    * @abstract Provides preliminary setup for new modal window
    */
   __setup: function(o){
    if (_validation.__szCk(o.keys)>=3){
     var _win = '<div id="overlay"></div><div id="modal"><div id="content">'+_modal.__aK(o)+'</div></div>';
     $('#'+o.formID.attr('name')).prepend(_win);
     $('body').css({'overflow':'hidden'});
     $('#overlay').css({'position':'fixed','top':0,'left':0,'width':'100%','height':'100%','background':'#000','opacity':0.5,'filter':'alpha(opacity=50)'});
     $('#modal').css({'position':'absolute','background':'rgba(0,0,0,0.2)','border-radius':'14px','padding':'8px'});
     $('#content').css({'border-radius':'8px','background':'#fff','padding':'20px'});
    }
   },

   /**
    * @function __e
    * @abstract Executes the decryption and assignment within the global scope
    *           of the user selected public key while closing the modal window
    */
   __e: function(o, e){
    $.each(o.keys, function(a, b){
     if (_encrypt.__d(o.aes, b['email'], a)==e){
      o.use = _encrypt.__d(o.aes, b['key'], a);
      $('#keyring, #content, #modal, #overlay').hide();
      $('body').css({'overflow':'auto'});
     }
    });
    return o.use;
   },

   /**
    * @function __aK
    * @abstract Creates selectable list of current keys
    */
   __aK: function(o){
    var _s = _validation.__szCk(o.keys);
    var _d = (_s>=5) ? 5 : _s;
    var _x, _a = '';
    if (_s>=3){
     var _k = '';
     _x = '<label for="keyring">Select your email:</label><select name="keyring" id="keyring" size="'+_d+'" multiple>';
     $.each(o.keys, function(k, v){
      _k = _encrypt.__d(o.aes, v['email'], k);
      _a = /[0-9a-z-_.]{2,45}\@[0-9a-z-_.]{2,45}\.[a-z]{2,4}/i;
      if (_a.test(_k)){
       _x = _x + '<option value="'+_k+'">'+_k+'</option>';
      }
     });
     _x = _x + '</select>';
    }
    return _x;
   }
  }

  /**
   * @function __r
   * @abstract Function used help debug objects recursively
   */
  var __r = function(obj){
   $.each(obj, function(x,y){
    if (typeof y==='object'){
     console.log(x);
     __r(y);
    } else {
     console.log(x+' => '+y);
    }
   });
  }

  /* robot, do something */
  if (methods[method]){
   return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
  } else if ((typeof method==='object')||(!method)){
   return methods.init.apply(this, arguments);
  } else {
   console.log('Method '+method+' does not exist');
  }
 };
})(jQuery);



/*
  Implemented by Sandro Alves Peres
  sandrinhodobanjo@yahoo.com.br
*/

$f = {
  
  BY_ID: 1,
  BY_VALUE: 2,
  MASK_CEP: "#####-###",
  MASK_CPF: "###.###.###-##",
  MASK_CNPJ: "##.###.###/####-##",
  MASK_DATE: "##/##/####",
  MASK_TIME: "##:##:##",  
  MASK_SHORT_TIME: "##:##",  
  MASK_FONE: "(##)####-####",
  FORMAT_BR: 1,
  FORMAT_SQL: 2,
  TIME_FULL: 1,  
  TIME_SHORT: 2,
   
  
  $: function( str_id ){
	 if( document.getElementById ){
        return document.getElementById( str_id );
	 }
	 
	 if( !document.getElementById && document.all ){
		return document.all[ str_id ];
	 }
  },
  
  
  $$_str: "",     // used in $f.cbboxSearch
  $$_timeout: 0,  // used in $f.cbboxSearch

  cbboxSearch: function( sel, e ){ // put [ onkeypress="$f.cbboxSearch(this, event); return false;" ] of the select
    var i=0, c=true;
	var key = (window.event ? e.keyCode : e.which);
	
    $f.$$_str = $f.$$_str + String.fromCharCode(key);
    $f.$$_str = $f.$$_str.toLowerCase();
	
    while(c){
      var textOpt = sel.options[i].text.toLowerCase();
      var strOpt = textOpt.substr(0, ($f.$$_str.length));
		
      if(strOpt == $f.$$_str){
        sel.options[i].selected = true;
        c = false;
      }
      if(i >= (sel.options.length - 1)){
        c = false;
      }
      i++;
    }
	
    clearTimeout($f.$$_timeout);
	$f.$$_timeout = setTimeout("clearTimeout($f.$$_timeout); $f.$$_str='';", 2000);
  },
  
  
  $$_background: null, // used in $f.paint
  $$_foreground: null, // used in $f.paint
  $$_fontWeight: null, // used in $f.paint
  $$_fontStyle: null,  // used in $f.paint  
    
  paint: function( obj, colorBack, colorFore, fontWeight, fontStyle){
	$f.$$_background = null;
	$f.$$_foreground = null;
	$f.$$_fontWeight = null;  
	$f.$$_fontStyle  = null;	
	  
    if(typeof(colorFore) != "undefined"){
	  $f.$$_foreground = obj.style.color;
	  obj.style.color = colorFore;  
    }
	
    if(typeof(fontWeight) != "undefined"){
	  $f.$$_fontWeight = obj.style.fontWeight;
	  obj.style.fontWeight = fontWeight;  
    }		
	
    if(typeof(fontStyle) != "undefined"){
	  $f.$$_fontStyle = obj.style.fontStyle;
	  obj.style.fontStyle = fontStyle;  
    }	
   
    $f.$$_background = obj.style.backgroundColor;
    obj.style.backgroundColor = colorBack;	
  },


  unpaint: function( obj ){
	if($f.$$_background != null){
      obj.style.backgroundColor = $f.$$_background;
	}
  
    if($f.$$_foreground != null){
      obj.style.color = $f.$$_foreground;
    }
	
    if($f.$$_fontWeight != null){
      obj.style.fontWeight = $f.$$_fontWeight;
    }			
	
    if($f.$$_fontStyle != null){
      obj.style.fontStyle = $f.$$_fontStyle;
    }	
  
	$f.$$_background = null;
	$f.$$_foreground = null;
	$f.$$_fontWeight = null;
	$f.$$_fontStyle  = null;	
  },  
  
  
  utf8_encode: function( s ) {
	var c, d = "";
	for (var i = 0; i < s.length; i++) {
	  c = s.charCodeAt(i);
	  if (c <= 0x7f) {
		d += s.charAt(i);
	  } else if (c >= 0x80 && c <= 0x7ff) {
		d += String.fromCharCode(((c >> 6) & 0x1f) | 0xc0);
		d += String.fromCharCode((c & 0x3f) | 0x80);
	  } else {
		d += String.fromCharCode((c >> 12) | 0xe0);
		d += String.fromCharCode(((c >> 6) & 0x3f) | 0x80);
		d += String.fromCharCode((c & 0x3f) | 0x80);
	  }
	}
	return d;
  }, 
  
  
  utf8_decode: function( s ) {
	var c, d = "", flag = 0, tmp;
	for (var i = 0; i < s.length; i++) {
	  c = s.charCodeAt(i);
	  if (flag == 0) {
		if ((c & 0xe0) == 0xe0) {
		  flag = 2;
		  tmp = (c & 0x0f) << 12;
		} else if ((c & 0xc0) == 0xc0) {
		  flag = 1;
		  tmp = (c & 0x1f) << 6;
		} else if ((c & 0x80) == 0) {
		  d += s.charAt(i);
		} else {
		  flag = 0;
		}
	  } else if (flag == 1) {
		flag = 0;
		d += String.fromCharCode(tmp | (c & 0x3f));
	  } else if (flag == 2) {
		flag = 3;
		tmp |= (c & 0x3f) << 6;
	  } else if (flag == 3) {
		flag = 0;
		d += String.fromCharCode(tmp | (c & 0x3f));
	  } else {
		flag = 0;
	  }
	}
	return d;
  },  


  getAjax: function(){
    if( window.XMLHttpRequest ) return new XMLHttpRequest();

    if( window.ActiveXObject ){
	   var msxmls = ['Msxml2.XMLHTTP.5.0', 'Msxml2.XMLHTTP.4.0', 'Msxml2.XMLHTTP.3.0', 'Msxml2.XMLHTTP', 'Microsoft.XMLHTTP'];
	   for(var i=0; i < msxmls.length; i++){
		  try{
			 return new ActiveXObject( msxmls[i] );
		  }
		  catch(e){}
	   }		  
    }
	
    return null;
  },
 
 
  getCookie: function( check_name ){
	var a_all_cookies  = document.cookie.split(';');
	var a_temp_cookie  = '';
	var cookie_name    = '';
	var cookie_value   = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for(var i=0; i < a_all_cookies.length; i++){
	  // now we'll split apart each name=value pair
	  a_temp_cookie = a_all_cookies[i].split('=');
	  
	  // and trim left/right whitespace while we're at it
	  cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
  
	  // if the extracted name matches passed check_name
	  if( cookie_name == check_name ){
		  b_cookie_found = true;
		  // we need to handle case where cookie has no value but exists (no = sign, that is):
		  if( a_temp_cookie.length > 1 ){
			 cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
		  }
		  // note that in cases where cookie is initialized but no value, null is returned
		  return cookie_value;
		  break;
	  }
	  
	  a_temp_cookie = null;
	  cookie_name = '';
	}
	
	if( !b_cookie_found ){
	   return null;
	}
  },


  setCookie: function( name, value, expires, path, domain, secure ){ // only the first 2 parameters are required. Expires is for hours
	var today = new Date();
	today.setTime(today.getTime());

	if( expires ){
	  expires = expires * 1000 * 60 * 60;
	}

    var cookie = '';
	var expires_date = new Date(today.getTime() + (expires));

    cookie  = name + "=" + escape(value);
	cookie += (expires ? ";expires=" + expires_date.toGMTString() : "");
    cookie += (path ? ";path=" + path : "");
    cookie += (domain ? ";domain=" + domain : ""); 
    cookie += (secure ? ";secure" : "");	

	document.cookie = cookie;	
  },


  deleteCookie: function( name, path, domain ){
	var cookie = '';
	
	if( $f.getCookie(name) ){
	  cookie  = name + "=" + (path ? ";path=" + path : "");
	  cookie += (domain ? ";domain=" + domain : "");
	  cookie += ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	  document.cookie = cookie;
	}
  },  
 
 
  preventDefault: function( ev ){
	if( typeof(ev.preventDefault) != "undefined" ){
	  ev.preventDefault();
	}	
  },
    
  
  isAcceptedFormat: function( __name, __allowEmpty, __formats ){ // for input files, separate by comma the formats or "*" for all
    if(typeof(__formats) == "undefined") var __formats = "*";  // default
	__formats = __formats.toLowerCase();
	
	var __accepted = true;
	var __files = document.getElementsByName(__name);
	for(var i=0; i < __files.length; i++){
	  if(__allowEmpty && $f.empty(__files.item(i).value, 2)){
		continue;  
	  }
	  else{
		if(! __allowEmpty && $f.empty(__files.item(i).value, 2)){
		  __accepted = false;
		  break;
		}
		else{
		  var __pieces = (new String(__files.item(i).value)).split(".");
		  
		  if(__pieces.length >= 2){
			if(__formats == "*") continue;
			  
			var __arrFormats = __formats.replace(/\s+/gi, "").split(",");
			if($f.inArray((new String(__pieces[__pieces.length-1])).toLowerCase(), __arrFormats)){
			  continue;	
			}
			else{
			  __accepted = false;
			  break;
			}
		  }
		  else{
			__accepted = false; 
			break;
		  }
		}
	  }
	}
	
	return __accepted;
  },
  

  isLeapYear: function( __year ){
    if((__year % 4) == 0 && ((__year % 100) != 0 || (__year % 400) == 0)){
	  return true;
	}
	else{
	  return false;	
	}
  },
  
  
  getViewportHeight: function(){
	if( window.innerHeight != window.undefined )
	return window.innerHeight;
	
	if( document.compatMode == 'CSS1Compat' )
	return document.documentElement.clientHeight;
	
	if( document.body )
	return document.body.clientHeight; 

	return window.undefined; 
  },


  getViewportWidth: function(){
	if( window.innerWidth != window.undefined )
	return window.innerWidth; 
	
	if( document.compatMode == 'CSS1Compat' )
	return document.documentElement.clientWidth; 
	
	if( document.body )
	return document.body.clientWidth; 
  },


  getScrollTop: function() {
	if( self.pageYOffset ){// all except Explorer
	   return self.pageYOffset;
	}
	else if( document.documentElement && document.documentElement.scrollTop ){ // Explorer 6 Strict
	   return document.documentElement.scrollTop;
	}
	else if( document.body ){ // all other Explorers
	   return document.body.scrollTop;
	}
  },


  getScrollLeft: function() {
	if( self.pageXOffset ){ // all except Explorer
	   return self.pageXOffset;
	}
	else if( document.documentElement && document.documentElement.scrollLeft ){ // Explorer 6 Strict
	   return document.documentElement.scrollLeft;
	}
	else if( document.body ){ // all other Explorers
	   return document.body.scrollLeft;
	}
  },
  
  
  datediff: function( _date1, _date2 ){ // format dd/mm/yyyy
    var date1 = new String(_date1);
	var date2 = new String(_date2);
	return ($f.todays(date1) - $f.todays(date2));
  },
  
  
  todays: function(_date){ // format dd/mm/yyyy
	var days  = 0, days29 = 0;  
	var _date = (new String(_date)).split("/");
	var daysMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
	
	_date[0] = parseInt(_date[0], 10);
	_date[1] = parseInt(_date[1], 10);
	_date[2] = parseInt(_date[2], 10);
	
	for(var i=1; i < _date[2]; i++){
      if($f.isLeapYear(i)){
	    days29++;
      }	  	
	}
    
	if($f.isLeapYear(_date[2])){
	  if(_date[1] > 2 || (_date[1]==2 && _date[0]==29)){
		daysMonth[1] = 29;
	  }
	}
	
	for(var i=0; i <= (_date[1] - 2); i++){
	  days += daysMonth[i];
	}
	
	days += ((_date[2] * 365) + _date[0] + days29);
	return days;
  }, 
  
  
  timediff: function( _time1, _time2 ){
    var _time1 = new String(_time1);
	var _time2 = new String(_time2);
	return ($f.tosecs(_time1) - $f.tosecs(_time2));
  }, 
  

  tosecs: function( _time ){
	if($f.isTime(_time, 2)){
	  var arrTime = (new String(_time)).split(":");
	  arrTime[0] = parseInt(arrTime[0], 10);
	  arrTime[1] = parseInt(arrTime[1], 10);
	  arrTime[2] = parseInt(arrTime[2], 10);
	  
	  var seconds = (arrTime[0] * Math.pow(60, 2));
	  seconds += ((arrTime[1] * 60) + arrTime[2]);
	  
	  return seconds;
	}
	else{
	  return 0;	
	}
  },
  
  
  lockKeys: function( ev ){ // put code of keys after event or use a string with the keys to lock (return lockKeys(event, 13, 9) || return lockKeys(event, "a[]{}@+", 13)
    var key = (window.event ? ev.keyCode : ev.which);
 
    for(var i=1; i < arguments.length; i++){
	  if(typeof(arguments[i]) == "number"){
		if(key == arguments[i]){
		  return false;
		}
	  }
	  else if(typeof(arguments[i]) == "string"){
		for(var j=0; j < arguments[i].length; j++){
		  if(key == arguments[i].charCodeAt(j)){
			return false;
		  }
		}
	  }
	}
	
	return true;
  },
  
  
  allowOnlyEmailKeys: function( ev ){ // onkeypress="return allowOnlyEmailKeys( event );"
    var val = $f.getEvent(ev).target.value;
  
    if( val.indexOf("@") > -1 && $f.getEvent(ev).charCode == 64 ){
	  return false;	
	}
	
	return $f.lockKeys(ev, '[]{}%#$^~´`?!|\\/=+,*¨;:()&§ºª°¢¹²³£¬<>', 32, 34, 39);
  },
  
  
  htmlentities: function( _text ){
    var char, entity="";
    var _text = new String(_text);
  
    for(var i=0; i < _text.length; i++){
	  char = _text.charCodeAt(i);
	  if((char > 47 && char < 58) || (char > 62 && char < 127)){            
	    entity += _text.charAt(i);
	  }
	  else{
	    entity += "&#" + _text.charCodeAt(i) + ";";
	  }
    }
    return entity;
  },
  
  
  addFavorite: function( url, title ){
    if( window.sidebar ){
  	  window.sidebar.addPanel(title, url, "");
	}
    else if( window.opera && window.print ){
      var o = document.createElement("a");
      o.setAttribute("rel", "sidebar");
      o.setAttribute("href", url);
      o.setAttribute("title", title);
      o.click();
    }
    else if( document.all ){
	  window.external.AddFavorite(url, title);
	}
  },  
  
  
  removeNode: function( id_obj ){
    var pNode = $f.$(id_obj).parentNode;
	var cNode = $f.$(id_obj);
    pNode.removeChild(cNode);
  },
  
  
  randomCode: function( _size ){ // max 12
    var s = (Math.abs(_size) > 12 ? 12 : Math.abs(_size));
	var base = new Array();
	base[0] = ((new Date()).getMilliseconds() * (new Date()).getSeconds());
	base[1] = (base[0] * 2);
	base[2] = Math.round(base[1] / 3);
	var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    var _code = (new String(base.join(""))).split("");
	var strCode = "";
	
	for(var i in _code){
	  if((i + parseInt(_code[i], 10)) > 25){
		var pos = Math.floor(_code[i] / 2.5);
		strCode += (pos * 2) + chars.charAt(pos);  
	  }
	  else{
		strCode += Math.ceil(parseInt(_code[i], 10) * 1.5) + chars.charAt(parseInt(_code[i], 10));
	  }
	}
	
	strCode = strCode.toUpperCase();
	
	if((new Date()).getSeconds() % 2 == 0){
	  strCode = strCode.substr(0, s); 	
	}
	else{
	  strCode = strCode.slice(-s);	
	}
	
	return strCode;	
  },
  
  
  daysOfMonth: function(month, year){
    if(month < 8 && (month % 2) == 1 || month > 7 && (month % 2) == 0){
	  return 31;
    }
    if(month != 2){
	  return 30; 
    }
    if($f.isLeapYear(year)){
	  return 29;
    }
    return 28;
  }, 


  adddate: function( __identifier, days, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
    var arrdate = __identifier.split("/");
    var Month   = parseInt(arrdate[1], 10);
    var Year    = parseInt(arrdate[2], 10);
  
    if(days >= 0){
      var AddedDay = parseInt(arrdate[0], 10);
	  AddedDay += days;
	  
      while(AddedDay > $f.daysOfMonth(Month, Year)){
	    AddedDay -= $f.daysOfMonth(Month, Year);
	    Month++; 
	    if(Month > 12){
	      Month = 1;
	      Year++;
	    }
      }
    }
    else{
	  var AddedDay = parseInt(arrdate[0], 10);
      for(var i=0; i < (days * -1); i++){
	    if(AddedDay > 1){
	      AddedDay--;
	    }
	    else{
	      if(Month > 1){
		    Month--;
		  }
		  else{
		    Month=12;
		    Year--;
		  }
		  AddedDay = $f.daysOfMonth(Month, Year);
	    }
	  }							
    }
  
    AddedDay = $f.lpad(AddedDay, 2);
    Month    = $f.lpad(Month, 2);
    Year     = $f.lpad(Year, 4);
  
    return AddedDay.concat("/", Month, "/", Year);
  },


  insertAtCursor: function( idField, myValue ){
    var myField = $f.$(idField);
    if( document.selection ){ //IE
      myField.focus();
      var sel  = document.selection.createRange();
      sel.text = myValue;
    } // Mozila, NetScape
    else if( myField.selectionStart || myField.selectionStart == "0" ){
      var startPos  = myField.selectionStart;
      var endPos    = myField.selectionEnd;
      myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
    }
    else{
      myField.value += myValue;
    }
  },


  isIE: function(){
	var userAgent = navigator.userAgent.toString();  
	  
    if(document.all && userAgent.match(/MSIE.([0-9\.]*)/i)){
      return true;
    }
    else{
      return false;
    }
  },

  
  isOpera: function(){
    var nav = navigator.appName.toString();
	var userAgent = navigator.userAgent.toString();  	
	 
    if(nav.match(/^Opera$/i) && userAgent.match(/Opera.([0-9\.]*)/i)){
      return true;
    }
    else{
      return false;
    }	  
  },
  
  
  isSafari: function(){
	var userAgent = navigator.userAgent.toString(); 	  
	  
    if(userAgent.match(/(applewebkit|safari)\/([\d\.]*)/i) && !$f.isIE() && !$f.isOpera()){
	  return true;	
	}
	else{
	  return false;	
	}
  },

  
  isMozillaLine: function(){
	var userAgent = navigator.userAgent.toString(); 	  
	  
    if(userAgent.match(/Mozilla|Firefox|Gecko/gi)){
	  return true;	
	}
	else{
	  return false;	
	} 	  
  },


  isDownCapsLock: function( ev ){
    var e = ev || window.event;
    var _keyCode  = e.keyCode ? e.keyCode : e.which;
    var _keyShift = e.shiftKey ? e.shiftKey : ((_keyCode == 16) ? true : false);

    if(((_keyCode >= 65 && _keyCode <= 90) && !_keyShift) || ((_keyCode >= 97 && _keyCode <= 122) && _keyShift)){
      return true;
    }
    else{
      return false;
    }
  },


  inArray: function( objValue, array ){
    __return=false;
  
    for(var i in array){
      if(array[i] == objValue){
	     __return = true;
		 break;
	  }
    } 
	
    return __return;
  },
  
  
  inMatrix: function( objValue, matrix ){ // bidimensional
    __return=false;
  
    for(var i in matrix){
	  for(var j in matrix[i]){
		if(matrix[i][j] == objValue){
		   __return = true;
		   break;	
		}
	  }
    } 
	
    return __return;	  
  },


  addEvent: function( idobj, ev, func, useCapture ){
    if(window.addEventListener){
      $f.$(idobj).addEventListener(ev, func, useCapture); // Mozilla, Chrome
    }
    else if(window.attachEvent){
      $f.$(idobj).attachEvent("on" + ev, func); // IE
    }  
  },
  
  
  removeEvent: function( idobj, ev, func, useCapture ){
    if(window.addEventListener){
      $f.$(idobj).removeEventListener(ev, func, useCapture); // Mozilla, Chrome 
    }
    else if(window.attachEvent){
      $f.$(idobj).detachEvent("on" + ev, func); // IE
    }  
  },  


  addWindowEvent: function( ev, func, useCapture ){
    if(window.addEventListener){
      window.addEventListener(ev, func, useCapture); // Mozilla, Chrome
    }
    else if(window.attachEvent){
      window.attachEvent("on" + ev, func); // IE
    }
  },
  
  
  removeWindowEvent: function( ev, func, useCapture ){
    if(window.addEventListener){
      window.removeEventListener(ev, func, useCapture); // Mozilla, Chrome
    }
    else if(window.attachEvent){
      window.detachEvent("on" + ev, func); // IE
    }
  },  


  fckGetText: function( id ){ // gets the text from FCKEditor
    var theEditor = FCKeditorAPI.GetInstance(id);
    var _text     = theEditor.GetXHTML();
    return _text;
  },


  fckSetText: function( id, _text, clean ){
    var theEditor = FCKeditorAPI.GetInstance(id);
    theEditor.SetData(_text, clean);
  },
  
  
  fckFocus: function( id ){
    var theEditor = FCKeditorAPI.GetInstance(id);
    theEditor.Focus();
  }, 
  

  fckIsEmpty: function( id ){
    if($f.stripSpace($f.trim($f.stripTags($f.fckGetText(id), 2), 2), 2) == ""){
	  return true;	
	}
	else{
	  return false;	
	}
  },


  stripTags: function( __identifier, __option ){ // gi=global search
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
    __identifier = __identifier.replace(/^\s*/, "");
    __identifier = __identifier.replace(/\s*$/, "");  
    __identifier = __identifier.replace(/<[^>]*>/gi, "");
    return __identifier;
  },


  stripSpace: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }

    __identifier = __identifier.replace(/&nbsp;/gi, "");
    return __identifier;
  },


  lpad: function( __value, __size, __fillWith ){
	if(typeof(__fillWith) == "undefined"){ __fillWith = "0"; }
	
	if(__fillWith.length == 0 || __fillWith.length > 1){
	  throw new Error("Value of filling must have length 1.");	
	}
	
	__value = new String(__value);
	
    if(__value.length >= __size){
	  return __value;
    }	
	
	for(var i=0; i <= __size; i++){
      __value = __fillWith + __value;	
	}

    return __value.slice(-__size); // copy back when it is negative
  },
  
  
  rpad: function( __value, __size, __fillWith ){
	if(typeof(__fillWith) == "undefined"){ __fillWith = "0"; }
	
	if(__fillWith.length == 0 || __fillWith.length > 1){
	  throw new Error("Value of filling must have length 1.");	
	}
	
    var v = new String(__value);
	
	if(v.length < __size){
	  var diff = __size - v.length;
	  for(var i=0; i < diff; i++){
	    v += __fillWith;
	  }
	  return v;
	}
	else{
	  return v;	
	}    
  },  
  
  
  div: function( n1, n2 ){ // operator div
	return (n2 > n1 ? 0 : (n1 == n2 ? 1 : Math.floor(n1 / n2)));
  },
   
  
  formatFloat: function( __float, __dec, __thousandSep, __decPoint ){
	if(isNaN(__float)){
	  return 0;	
	}
	
	if(typeof(__dec) == "undefined"){ __dec = 2; }	
	if(typeof(__thousandSep) == "undefined"){ __thousandSep = "."; }
	if(typeof(__decPoint) == "undefined"){ __decPoint = ","; }	
	
    var strNum     = new String(__float);
	var isNegative = (strNum.charAt(0) == "-" ? true : false);
	var strDec     = "";
	
	if(isNegative){
	  strNum = strNum.replace(/^[-]+/i, "");
	}

	if(strNum.indexOf(".") == -1){
	  strDec = $f.lpad(strDec, __dec, "0");
	  strNum = strNum.concat(".", strDec);
	}
	
	var arrV = [];
	arrV     = strNum.split(".");
    arrV[1]  = $f.rpad(arrV[1], __dec, "0");
	
	var arrNum  = [];	
	var sizeNum = arrV[0].length;
	
	arrNum = arrV[0].split("");	
	arrNum.reverse();
	arrV[0] = arrNum.join("");
    
	var arrN = new Array();
	
    for(var i=0; i < sizeNum; i += 3){
	  arrNum = [];
	  arrNum = (arrV[0].substr(i,3)).split("");
	  arrNum.reverse();
	  arrN.push(arrNum.join(""));
	}
	
	arrN.reverse();
	var number = (isNegative ? "-" : "") + arrN.join(__thousandSep) + __decPoint + arrV[1];
	
	return number;	
  },


  formatDate: function( __identifier, __option, formatTo ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
	
	if(typeof(formatTo) == "undefined"){
	  formatTo = $f.FORMAT_SQL;	
	}
	
	var arrTime = [];
	if(formatTo == $f.FORMAT_SQL){
      arrTime = __identifier.split("/");
      arrTime.reverse();
	  return arrTime.join("-");
	}
	else{
      arrTime = __identifier.split("-");
      arrTime.reverse();
	  return arrTime.join("/");		
	}    
  },


  isDate: function( __identifier, __option ){
   if(typeof(__option) == "undefined"){
     var __identifier = new String($f.$(__identifier).value);
   }
   else if(__option == $f.BY_VALUE){
     var __identifier = new String(__identifier); 
   }  
   else{ // catches by id
     var __identifier = new String($f.$(__identifier).value);
   }	
	
   var arrDate = new Array();
   arrDate = __identifier.split("/");
   var __return = false;
   var DaysMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   
   if(! /^\d{2}\/\d{2}\/\d{4}$/.test(__identifier)){
	 return false;
   }
 
   var Day   = parseInt(arrDate[0], 10);
   var Month = parseInt(arrDate[1], 10);
   var Year  = parseInt(arrDate[2], 10);		 
	 
   if($f.isLeapYear(Year)){
     DaysMonth[1] = 29; // February in leap year
   }
	   
   if(Year > 0){
     if(Month > 0 && Month <= 12){
       if(Day > 0 && Day <= DaysMonth[(Month-1)]){
         __return = true;
       }
       else{
         __return = false;  
       }
     }
     else{
       __return = false;
     }
   }
   else{
     __return = false;
   }	 
 
   return __return;  
  },


  isCurrentDate: function( __identifier, __option, _strDateServer ){ // date must be true -> validating through the IsDate() | strDateServer = dd/mm/yyyy
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }

    var arrDate = new Array();
    arrDate = __identifier.split("/");
    var __return = false;
    var Day   = parseInt(arrDate[0], 10);
    var Month = parseInt(arrDate[1], 10);
    var Year  = parseInt(arrDate[2], 10); 

    var SysDate = new Date();
	if(typeof(_strDateServer) != "undefined"){
	  var arrDateServer=(new String(_strDateServer)).split("/");
	  SysDate.setDate(parseInt(arrDateServer[0], 10));
	  SysDate.setMonth(parseInt(arrDateServer[1], 10)-1);
	  SysDate.setYear(parseInt(arrDateServer[2], 10));	  
	}

    var SysYear  = parseInt(SysDate.getFullYear(), 10);
    var SysMonth = parseInt(SysDate.getMonth()+1, 10);
    var SysDay   = parseInt(SysDate.getDate(), 10);
 
    if(Year > SysYear){
      __return = true;
    }
    else if(Year == SysYear){
      if(Month > SysMonth){
        __return = true;
      }
      else if(Month == SysMonth){
        if(Day >= SysDay){
	      __return = true; 
	    }
	    else{
	      __return = false;
	    }
      }
      else{
        __return = false;
      }
    }
    else{
      __return = false;
    }
 
    return __return;
  },


  isTime: function(__identifier, __option, __format){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
	
	var format = (typeof(__format) != "undefined" ? __format : $f.TIME_FULL);
	
	switch(format){
	  case 1:
	    if(! /^\d{2}:\d{2}:\d{2}$/.test(__identifier)){
	      return false;
		}
	  break;
	  
	  case 2:
	    if(! /^\d{2}:\d{2}$/.test(__identifier)){
		  return false;
		}
	  break;
	  
	  default:
	    throw new Error("Time Format is not defined!!!");
	  break;		
	}
	
    var arrTime  = new Array();
    var __return = false;		
    arrTime      = __identifier.split(":");

    var __hours   = parseInt(arrTime[0], 10);	
    var __minutes = parseInt(arrTime[1], 10);
	
	if(format == $f.TIME_FULL){	
      var __seconds = parseInt(arrTime[2], 10);	
	}
		
    if(__hours >= 0 && __hours <= 23){
      if(__minutes >= 0 && __minutes <= 59){
		  
		if(format == $f.TIME_SHORT){
		  return true;	
		}
		  
        if(__seconds >= 0 && __seconds <= 59){
          return true; 
        }
        else{
          return false;	  
        }
		
      }
      else{
        return false; 
      }
    }
    else{
      return false; 
    }
  },


  noNumbers: function(ev){ // use on onkeypress [ return noNumbers() ]
    var key = (window.event ? ev.keyCode : ev.which);
 
    if(key > 47 && key < 58){
      return false;
    }
    else{   
      return true;
    }
  },


  isFone: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }	

    if(/^\(\d{2}\)\d{4}-\d{4}$/.exec(__identifier)){
      return true;
    }
    else{
      return false;
    }
  },


  isCEP: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }	
 
    if(/^\d{5}-\d{3}$/.test(__identifier)){
      return true;
    }
    else{
      return false;
    }
  },


  setFormat: function( mask, object ){ // put on OnKeyPress = "$f.setFormat('##/##/####', this)"
    object.maxLength = (new String(mask)).length;  
    var __len  = object.value.length;
    var __text = mask.substring(__len);

    if (__text.substring(0,1) != "#"){
	  object.value += __text.substring(0,1);
    }
  },
  

  getPos: function(object){
    var currLeft = 0;
	var currTop  = 0;
	var objLeft  = object;
	var objTop   = object;
  
    if( objLeft.offsetParent ){
      while( objLeft.offsetParent ){
        currLeft += objLeft.offsetLeft;
        objLeft = objLeft.offsetParent;
      }
    }
  
    if( objTop.offsetParent ){
      while( objTop.offsetParent ){
        currTop += objTop.offsetTop;
        objTop = objTop.offsetParent;
      }
    } 
	
    return {x:currLeft, y:currTop};
  },
  
  
  getXY: function(ev){ // mouse position
	var ev = (ev ? ev : window.event);  
	   
	if($f.isIE() || $f.isSafari()){
	  var x = ev.clientX + document.body.scrollLeft;
	  var y = ev.clientY + document.body.scrollTop;
	}
	else{
	  var x = ev.pageX;
	  var y = ev.pageY;
	}
	 
    return {x:x, y:y};
  },  


  moveList: function(id_fbox, id_tbox){ 
    var arrFbox   = new Array();
	var arrTbox   = new Array();
	var arrLookup = new Array();
    var fbox      = $f.$(id_fbox); // list from
    var tbox      = $f.$(id_tbox); // list to

    for(var i=0; i < tbox.options.length; i++){ 
      arrLookup[tbox.options[i].text]=tbox.options[i].value; 
      arrTbox[i]=tbox.options[i].text; 
    }
  
    var fLength=0;
	var tLength=arrTbox.length;
    for(var i=0; i < fbox.options.length; i++){ 
      arrLookup[fbox.options[i].text]=fbox.options[i].value; 
      if(fbox.options[i].selected && fbox.options[i].value != ""){ 
        arrTbox[tLength]=fbox.options[i].text; 
        tLength++; 
      } 
      else{ 
        arrFbox[fLength]=fbox.options[i].text; 
        fLength++; 
      } 
    } 

    arrFbox.sort(); 
    arrTbox.sort(); 
    fbox.length=0; 
    tbox.length=0;
  
    for(var c=0; c < arrFbox.length; c++){ 
      var no=new Option(); 
      no.value=arrLookup[arrFbox[c]]; 
      no.text=arrFbox[c]; 
      fbox[c]=no; 
    } 
  
    for(var c=0; c < arrTbox.length; c++){ 
      var no=new Option(); 
      no.value=arrLookup[arrTbox[c]]; 
      no.text=arrTbox[c]; 
      no.selected="selected";
      tbox[c]=no; 
    } 
  },


  empty: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
    
	if($f.trim(__identifier, 2)==""){
	  return true;	
	}
	else{
	  return false;	
	}
  },
  

  emptySelect: function(id){
    var _Length=$f.$(id).length;
    var __return=true;
  
    for(var i=0; i < _Length; i++){
      if($f.$(id).options[i].selected){
	    __return=false;
	    break;
	  }
    }
  
    return __return;
  },


  cleanSelect: function(id){
    var _Length=$f.$(id).length;
  
    for(var i=0; i < _Length; i++){
      $f.$(id).options[i].selected = false;
    }  
  },
  
  
  fullSelect: function(id){
    var _Length=$f.$(id).length;
  
    for(var i=0; i < _Length; i++){
      $f.$(id).options[i].selected = true;
    }  
  },  


  trim: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }   
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
    return __identifier.replace(/^\s*/, "").replace(/\s*$/, "");
  },


  isEmail: function( __identifier, __option ){
    var expEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{1,3})+$/; // regular expression for email
	
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
	if(__identifier.lastIndexOf(".") == (__identifier.length-1)){
	  return false;
	}
	
    var arrEmail = __identifier.split(".");
	try{
	  if((new String(arrEmail[arrEmail.length-1])).length >= 4){
		return false;  
	  }
	}
	catch(e){}  
    finally{
      return expEmail.exec(__identifier);
	}
  },


  isNumber: function( __identifier, __option ){
    var expression=/^\d{1,}$/;	
	
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
    return expression.exec(__identifier);
  },


  isFloat: function( __identifier, __option ){
    var expression=/^(\d+)(\.?)(\d*)$/;
	
    if(typeof(__option) == "undefined"){
      var __identifier = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var __identifier = new String(__identifier); 
    }  
    else{ // catches by id
      var __identifier = new String($f.$(__identifier).value);
    }
  
    return expression.test(__identifier);
  },


  isCPF: function( __identifier, __option ){
    __return = true;
  
    if(typeof(__option) == "undefined"){
      var CPF = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      var CPF = new String(__identifier);
    }  
    else{ // catches by id
      var CPF = new String($f.$(__identifier).value);
    }  
  
    if(! /^\d{3}\.\d{3}\.\d{3}-\d{2}$/.test(CPF)){
	  return false;	
	}
	
    CPF = CPF.replace(/[\.-]+/gi, "");
	
    if(/^0{11}|1{11}|2{11}|3{11}|4{11}|5{11}|6{11}|7{11}|8{11}|9{11}$/.test(CPF)){
      return false;
    }
	
	try{
	  var DIGITO = new Array(10);
	  var DV_INFORMADO = CPF.substr(9, 2);

	  for(var i=0; i <= 8; i++){
		DIGITO[i] = CPF.substr(i, 1);
	  }

	  var POSICAO = 10;
	  var SOMA = 0;

	  for(var i=0; i <= 8; i++){
		SOMA = (SOMA + DIGITO[i] * POSICAO);
		POSICAO = (POSICAO - 1);
	  }

	  DIGITO[9] = (SOMA % 11);

	  if(DIGITO[9] < 2){
		DIGITO[9] = 0;
	  }
	  else{
		DIGITO[9] = (11 - DIGITO[9]);
	  }

	  POSICAO = 11;
	  SOMA = 0;

	  for(var i=0; i <= 9; i++){
		SOMA = (SOMA + DIGITO[i] * POSICAO);
		POSICAO = (POSICAO - 1);
	  }

	  DIGITO[10] = (SOMA % 11);

	  if(DIGITO[10] < 2){
		DIGITO[10] = 0;
	  }
	  else{
		DIGITO[10] = (11 - DIGITO[10]);
	  }

	  var DV = (DIGITO[9] * 10 + DIGITO[10]);

	  if(DV != DV_INFORMADO){
		__return = false;
	  }
	}
	catch(e){
	  __return = false;
	}
  
    return __return;
  },


  isCNPJ: function( __identifier, __option ){
    if(typeof(__option) == "undefined"){
      CNPJ = new String($f.$(__identifier).value);
    }
    else if(__option == $f.BY_VALUE){
      CNPJ = new String(__identifier); 
    }  
    else{ // catches through the id
      CNPJ = new String($f.$(__identifier).value);
    }	
	
    __return = true;
  
    if(! /^\d{2}\.\d{3}\.\d{3}\/\d{4}-\d{2}$/.test(CNPJ)){
      return false;
    }

    CNPJ = CNPJ.replace(/\D/gi, "");
  
    var a = [];
    var b = new Number();
    var c = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2];

    for(var i=0; i < 12; i++){
      a[i] = CNPJ.charAt(i);
      b   += (a[i] * c[i+1]);
    }
  
    if((x=b % 11) < 2){
      a[12] = 0;
    }
    else{
	  a[12] = (11-x);
    }
  
    b = 0;
    for(var y=0; y < 13; y++){
      b += (a[y] * c[y]); 
    }

    if((x=b % 11) < 2){
	  a[13] = 0;
    }
    else{
	  a[13] = (11-x);
    }
  
    if((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
      __return = false;
    }
               
    return __return;
  },
   

  getEvent: function( ev ){
    var ev = (ev ? ev: (window.event ? window.event : null));
  
    if( ev ){
      originalEvent = ev;
      type    = ev.type;
      screenX = ev.screenX;
      screenY = ev.screenY;
      target  = (ev.target ? ev.target : ev.srcElement); // IE: srcElement
      
      if( ev.modifiers ){ // N4: modifiers
        altKey   = ev.modifiers & Event.ALT_MASK;
        ctrlKey  = ev.modifiers & Event.CONTROL_MASK;
        shiftKey = ev.modifiers & Event.SHIFT_MASK;
        metaKey  = ev.modifiers & Event.META_MASK;
      }
      else{
        altKey   = ev.altKey;
        ctrlKey  = ev.ctrlKey;
        shiftKey = ev.shiftKey;
        metaKey  = ev.metaKey;
      }

      // N4: which // N6+: charCode
      charCode = (!isNaN(ev.charCode) ? ev.charCode : (!isNaN(ev.keyCode) ? ev.keyCode : ev.which));
      keyCode  = (!isNaN(ev.keyCode) ? ev.keyCode : ev.which);
      button   = (!isNaN(ev.button) ? ev.button : (!isNaN(ev.which) ? ev.which-1 : null));
      debug    = ("c:"+ev.charCode+" k:"+ev.keyCode+" b:"+ev.button+" w:"+ev.which);
    }
	
	return {
	  target: target,
	  type: type,
	  screenX: screenX,
	  screenY: screenY,
      altKey: altKey,
      ctrlKey: ctrlKey,
      shiftKey: shiftKey,
      metaKey: metaKey,
      charCode: charCode,
      keyCode: keyCode,
      button: button
	}
  }  
  
} /* end class */


if( !window.open ){ // Implementation to supply the BUG of IE8
  $f.addWindowEvent("load", function(){ 
	var ANCHOR_WINDOW_OPEN = document.createElement("a");
	ANCHOR_WINDOW_OPEN.setAttribute("id", "ANCHOR_WINDOW_OPEN");
	ANCHOR_WINDOW_OPEN.setAttribute("href", "#");
	ANCHOR_WINDOW_OPEN.setAttribute("target", "_blank");
	ANCHOR_WINDOW_OPEN.innerHTML = "ANCHOR_WINDOW_OPEN";
	ANCHOR_WINDOW_OPEN.style.cssText = "display:none; visibility:hidden";
	document.body.appendChild( ANCHOR_WINDOW_OPEN );
  }, false);
	
  window.open = function( url ){
	try{
	  $f.$("ANCHOR_WINDOW_OPEN").setAttribute("href", url);
	  $f.$("ANCHOR_WINDOW_OPEN").click();
	}
	catch(e){}
  
	return {
	  focus: function(){},
	  close: function(){}, 
	  alert: function( msg ){ alert(msg); },
	  confirm: function( msg ){ return confirm(msg); }
	}
  }
}